Mugunthan Balakrishnan
Mugunthan Balakrishnan

Reputation: 865

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

Upvotes: 3

Views: 13007

Answers (2)

tebs1200
tebs1200

Reputation: 1195

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.

Upvotes: 1

TheAppMentor
TheAppMentor

Reputation: 1099

Its not clear what you mean by "align". Assuming you want them one stacked one below another, I have made minor adjustments to your code.

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.

    let 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))
        let label = UILabel(frame: CGRectMake(getMainViewX, CGFloat(i) * 21, 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.
}

}

Hopefully this is how you are looking to align the labels

Upvotes: 1

Related Questions