Different position for different elements

Hello guys!

In SwiftUI is there a function to show different objects in random order or can I just do this by assigning the coordinates to each individual element?

For example, suppose I have a lot of circles, and I want to position them randomly, how can I do it?

Thanks in advance.

It depends on your design.

  • if you have predefined positions in an array (posArray: [CGPoint]) of items and want to show objects using one of this random positions

Then you can randomise the array of objects (objectsArray) in a computed var randomObjects And draw them using the posArray to get their position

  • Or you may have a struct for object, including a position
struct MyCircle {
    var radius: Int
    var pos: CGPoint {
        let x = (0...500).randomElement()!
        let y = (0...800).randomElement()!
        return CGPoint(x: x, y: y)
    }
}

Then you create the array of MyCircle and draw them

Note: if you want to redraw at random position, create a draw func that draws the circle

struct MyObject {
    var radius: Int
    var color: UIColor = .clear
    var pos: CGPoint {
        let x = (0...500).randomElement()!
        let y = (0...800).randomElement()!
        return CGPoint(x: x, y: y)
    }
    
    func draw() {
        print("pos", pos)
        // draw at pos with radius, filled with color
    }
}

Each time you call draw(), a new random position will be computed.

Thanks @Claude31 I tried this way but it gives an error

struct ContentView: View {
    var body: some View {
        MyCircle(radius: 3) // Static method 'buidBlock' requires that 'MyCircle' conform to 'View'
    }
}

struct MyCircle {
    var radius: Int
    var pos: CGPoint {
        let x = (0...500).randomElement()!
        let y = (0...500).randomElement()!
        return CGPoint(x: x, y: y)
    }
}

What did I do wrong?

Different position for different elements
 
 
Q