Mugunthan Balakrishnan Mugunthan Balakrishnan - 3 months ago 62
Swift Question

How to programmatically create UIlabel inside a custom uiView swift

how can i create 5 custom uilabel inside a custom

UIView
. Which will align one after the other. i have tried to create the
UILabel
inside the custom
UIView
. but it does not go inside the custom
UIView
.

//updated with the loop

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var mainView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

var getMainViewX = mainView.frame.origin.x
let getMainViewY = mainView.frame.origin.y

for var i = 0; i < 5; i++
{

let label = UILabel(frame: CGRectMake(getMainViewX, getMainViewY, 200, 21))
//label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
self.mainView.addSubview(label)
getMainViewX+=20
}

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}


the light gray box in the middle is the uiview

Answer

If you're using iOS 9, the recently added Stack View has been created for exactly this purpose.

  1. Use a UIStackView for your mainView instead of a default view
  2. You can set the alignment properties of the stack view in Interface Builder
  3. Create the labels in your loop, then add them to the stack view using the addArrangedSubview method of the stack view.

The stack view will take care of the alignment, spacing and layout of it's subviews for you.

Comments