Swift 3 Create UILabel programmatically and add NSLayoutConstraints

33,626

Solution 1

See below code as an example

let lblNew = UILabel()
lblNew.backgroundColor = UIColor.blue
lblNew.text = "Test"
lblNew.textColor = UIColor.white
lblNew.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lblNew)

let widthConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 300)
let heightConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
var constraints = NSLayoutConstraint.constraints(
    withVisualFormat: "V:[superview]-(<=1)-[label]",
    options: NSLayoutFormatOptions.alignAllCenterX,
    metrics: nil,
    views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

// Center vertically
constraints = NSLayoutConstraint.constraints(
    withVisualFormat: "H:[superview]-(<=1)-[label]",
    options: NSLayoutFormatOptions.alignAllCenterY,
    metrics: nil,
    views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

view.addConstraints([ widthConstraint, heightConstraint])

Solution 2

NSLayoutAnchor was new in iOS 9 and it greatly cleans up the constraint syntax.

let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray

self.contentView.addSubview(codedLabel)
codedLabel.translatesAutoresizingMaskIntoConstraints = false
codedLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
codedLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
codedLabel.centerXAnchor.constraint(equalTo: codedLabel.superview!.centerXAnchor).isActive = true
codedLabel.centerYAnchor.constraint(equalTo: codedLabel.superview!.centerYAnchor).isActive = true

Solution 3

let myLabel: UILabel = {
  let lb = UILabel()
  lb.translatesAutoresizingMaskIntoConstraints = false
  lb.textAlignment = .center
  lb.numberOfLines = 1
  lb.textColor = UIColor.black
  lb.font=UIFont.systemFont(ofSize: 22)
  lb.backgroundColor = UIColor.grey
  return lb
}()

In super.viewDidLoad() method, You need add label to your view and add contraints for the label:

override func viewDidLoad() {
  super.viewDidLoad()
  self.view.addSubView(myLabel)
  setUpMyLabel()
}

func setUpMyLabel() {
  NSLayoutConstraint.activate([
            myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7),
            myLabel.heightAnchor.constraint(equalToConstant: 50)])
}

I hope the my code can help to you.

Share:
33,626
iGeorge
Author by

iGeorge

Updated on July 17, 2022

Comments

  • iGeorge
    iGeorge almost 2 years

    Hello I am trying to create a label programmatically and add NSLayoutConstraints so that it is centered in the superview regardless of screen size and orientation etc. I have looked but just can't find an example to follow. Here is what I have:

    let codedLabel:UILabel = UILabel()
    codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
    codedLabel.textAlignment = .center
    codedLabel.text = alertText
    codedLabel.numberOfLines=1
    codedLabel.textColor=UIColor.red
    codedLabel.font=UIFont.systemFont(ofSize: 22)
    codedLabel.backgroundColor=UIColor.lightGray
    
    let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
    
    let widthConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
    
    codedLabel.addConstraints([heightConstraint, widthConstraint])
    
    let verticalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
    
    let horizontalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
    
    self.contentView.addConstraints([verticalConstraint, horizontalConstraint])
    
    self.contentView.addSubview(codedLabel)
    
  • iGeorge
    iGeorge over 7 years
    Thank you for that
  • iGeorge
    iGeorge over 7 years
    It looked daunting at first but is deceptively simple once someone shows you how - thank you
  • deijmaster
    deijmaster over 7 years
    Perfect and works flawlessly in iOS 10 and Xcode 8.2.
  • Protocole
    Protocole almost 7 years
    lblNew.translatesAutoresizingMaskIntoConstraints = false did the trick for me.