Mugunthan Balakrishnan Mugunthan Balakrishnan - 1 year ago 137
Swift Question

How to programmatically create UIlabel inside a custom uiView swift

how can i create 5 custom uilabel inside a custom

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

//updated with the loop

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var mainView: UIView!
override func 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))
// = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"


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


the light gray box in the middle is the uiview

Answer Source

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.