Search code examples
swiftframe

How to use frame to set x position in loop on Swift


I have an array that count is between 1 to 3 varies. I want to frame them in the middle of the screen with a certain distance Also the width of the labels is fixed

let array = ["some1", "some2", "some3"]

func setLabel(){
  var i = -1
  for text in array{
      i += 1
      let label = UILabel()
      label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
      label.text = text
      addSubview(label)
  }
}

enter image description here


Solution

  • You can use stackview as suggested by @matt. If you don't want to use stackview you can calculate the x position by array count and label index like this

    let array = ["some1", "some2", "some3"]
    func setLabel(){
        var i:CGFloat = 0
        for text in array{
            i += 1
            let label = UILabel()
            label.backgroundColor = .red
            label.frame = CGRect(x: (view.bounds.width/CGFloat(array.count+1))*i-25, y: 100, width: 50 , height: 20)
            label.text = text
            view.addSubview(label)
        }
    }