How to create UILabel programmatically using Swift?
Asked Answered
T

12

133

How do I create a UILabel programmatically using Swift in Xcode 6?

I have started with a new "Single View Application" in Xcode 6 and selected Swift for this project. I have my files AppDelegate.swift and ViewController.swift and I'm not sure what to do from here.

Trapeziform answered 6/6, 2014 at 12:21 Comment(1)
I suggest you start your study here: Swift documentation and work your way to Raywenderlich TutorialsUnboned
P
279

Creating a UILabel programmatically in Swift 3+:

override func viewDidLoad() {
    super.viewDidLoad()

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
    label.center = CGPoint(x: 160, y: 285)
    label.textAlignment = .center
    label.text = "I'm a test label"

    self.view.addSubview(label)
}
Privative answered 6/6, 2014 at 12:29 Comment(6)
You should not hard code the labels frame - what happens when text changes or text gets localized and changes the number of characters?Sacrament
You can also check this blog that describes programmatically adding UITextField, UITextView and UILabel: webindream.com/how-to-change-ui-elements-programmaticallyOpprobrium
@iSuresh how do you know that CGPoint(x:160, y: 285) is going to be center for the model they're using?South
But how to set up a UILabel that adjusts its width to the content?Vet
@Vet To do so, call label.sizeToFit().Cosher
Swift5.1 var label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) label.center = CGPoint(x: 160, y: 284) label.textAlignment = NSTextAlignment.center label.text = "I'm a test label" self.view.addSubview(label)Peplum
V
28

Here is the correct code for Swift 3, with comments for instructional purposes:

override func viewDidLoad()
{
    super.viewDidLoad()

    // CGRectMake has been deprecated - and should be let, not var
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))

    // you will probably want to set the font (remember to use Dynamic Type!)
    label.font = UIFont.preferredFont(forTextStyle: .footnote)

    // and set the text color too - remember good contrast
    label.textColor = .black

    // may not be necessary (e.g., if the width & height match the superview)
    // if you do need to center, CGPointMake has been deprecated, so use this
    label.center = CGPoint(x: 160, y: 284)

    // this changed in Swift 3 (much better, no?)
    label.textAlignment = .center

    label.text = "I am a test label"

    self.view.addSubview(label)
}
Viehmann answered 29/8, 2016 at 2:28 Comment(1)
Thanks Gourav - hope it helpedViehmann
O
18

Create UILabel view outside viewDidLoad class and then add that view to your main view in viewDidLoad method.

lazy var myLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "This is label view."
    label.font = UIFont.systemFont(ofSize: 12)
    return label
}()

And then add that view in viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myLabel)
    
    // Set its constraint to display it on screen
    myLabel.widthAnchor.constraint(equalToConstant:  200).isActive = true
    myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
Orbadiah answered 25/7, 2018 at 14:38 Comment(5)
@I Love Coding, can you please explain about your code. [lazy var myLabel: UILabel = { }() ]. It will helpful a lot. Thank you ....Bumgarner
@iOS When you create variable as lazy var variable_name = "" it will not consume your memory unless that variable is called by your app. If that property is not used then it will never execute.Orbadiah
Then we will create all variables as lazy in our project for better performance. Am I right?Bumgarner
@iOS yeah! Better use that variable type in your app for better performance. Also, you should be able to aware of Thread as well for better performance.Orbadiah
thank you. This really helped me with the concept of using lazyTrifocal
M
17

Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class.

  import UIKit

  class MyLabel: UILabel {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeLabel()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeLabel()
    }

    func initializeLabel() {

        self.textAlignment = .left
        self.font = UIFont(name: "Halvetica", size: 17)
        self.textColor = UIColor.white

    }

}

To use it, do the following

import UIKit

class ViewController: UIViewController {

     var myLabel: MyLabel()

     override func viewDidLoad() {
          super.viewDidLoad()

          myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
          self.view.addSubView(myLabel)
     }


}
Mask answered 4/10, 2017 at 3:39 Comment(3)
Just what I was looking for!Vonvona
Thank you man, I have a question, if I want to pass a string to self.text inside a class to iniciate like this: myLabel = MyLabel(string: "text")Marmite
I just find out how, using your class and calling like this: myLabel.text = "text"Marmite
B
16

Swift 4.X and Xcode 10

let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)

//To display multiple lines in label
lbl.numberOfLines = 0 //If you want to display only 2 lines replace 0(Zero) with 2.
lbl.lineBreakMode = .byWordWrapping //Word Wrap
// OR
lbl.lineBreakMode = .byCharWrapping //Charactor Wrap

lbl.sizeToFit()//If required
yourView.addSubview(lbl)

If you have multiple labels in your class use extension to add properties.

//Label 1
let lbl1 = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl1.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl1.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl1)

//Label 2
let lbl2 = UILabel(frame: CGRect(x: 10, y: 150, width: 230, height: 21))
lbl2.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl2.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl2)

extension UILabel {
    func myLabel() {
        textAlignment = .center
        textColor = .white
        backgroundColor = .lightGray
        font = UIFont.systemFont(ofSize: 17)
        numberOfLines = 0
        lineBreakMode = .byCharWrapping
        sizeToFit()
    }
}
Bumgarner answered 2/6, 2018 at 6:36 Comment(0)
S
11

You can create a label using the code below. Updated.

let yourLabel: UILabel = UILabel()
yourLabel.frame = CGRect(x: 50, y: 150, width: 200, height: 21)
yourLabel.backgroundColor = UIColor.orange
yourLabel.textColor = UIColor.black
yourLabel.textAlignment = NSTextAlignment.center
yourLabel.text = "test label"
self.view.addSubview(yourLabel)
Sowder answered 10/8, 2016 at 8:5 Comment(1)
I would add yourLabel.translatesAutoresizingMaskIntoConstraints = false so you can move your view with constraintsLudivinaludlew
O
9

Another answer in Swift 3:

let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)
Our answered 9/12, 2017 at 7:40 Comment(0)
E
6

Create label in swift 4

 let label = UILabel(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.size.width, height: 50))
    label.textAlignment = .center
    label.text = "Hello this my label"

    //To set the color
    label.backgroundColor = UIColor.white
    label.textColor = UIColor.black

    //To set the font Dynamic
    label.font = UIFont(name: "Helvetica-Regular", size: 20.0)

    //To set the system font
    label.font = UIFont.systemFont(ofSize: 20.0)

    //To display multiple lines
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping //Wrap the word of label
    label.lineBreakMode = .byCharWrapping //Wrap the charactor of label

    label.sizeToFit()
    self.view.addSubview(label)
Epigeous answered 7/12, 2018 at 6:25 Comment(0)
F
5

An alternative using a closure to separate out the code into something a bit neater using Swift 4:

class theViewController: UIViewController {

    /** Create the UILabel */
    var theLabel: UILabel = {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.textColor = UIColor.white
        label.textAlignment = .left
        label.numberOfLines = 3
        label.font = UIFont(name: "Helvetica-Bold", size: 22)
        return label
    }()

    override func viewDidLoad() {
        /** Add theLabel to the ViewControllers view */
        view.addSubview(theLabel)
    }

    override func viewDidLayoutSubviews() {
        /* Set the frame when the layout is changed */
        theLabel.frame = CGRect(x: 0,
                                y: 0,
                                width: view.frame.width - 30,
                                height: 24)
    }
}

As a note, attributes for theLabel can still be changed whenever using functions in the VC. You're just setting various defaults inside the closure and minimizing clutter in functions like viewDidLoad()

Faqir answered 11/4, 2018 at 21:36 Comment(1)
Beautiful technique...but it's not working for me in Xcode 9.4.1 ... unless I specify the frame somewhere in the computed value, whether in the constructor (UILabel(frame:)) or elsewhere in the block (label.frame=). Any later setting of the frame (e.g., in viewDidLayoutSubviews()) caused the label not to appear.Micron
C
3

Swift 4.2 and Xcode 10. Somewhere in ViewController:

private lazy var debugInfoLabel: UILabel = {
    let label = UILabel()
    label.textColor = .white
    label.translatesAutoresizingMaskIntoConstraints = false
    yourView.addSubview(label)
    NSLayoutConstraint.activate([
        label.centerXAnchor.constraint(equalTo: suggestionView.centerXAnchor),
        label.centerYAnchor.constraint(equalTo: suggestionView.centerYAnchor, constant: -100),
        label.widthAnchor.constraint(equalToConstant: 120),
        label.heightAnchor.constraint(equalToConstant: 50)])
    return label
}()

...

Using:

debugInfoLabel.text = debugInfo
Cubature answered 26/4, 2019 at 11:50 Comment(0)
H
1
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "My label"
self.view.addSubview(label)

Try above code in ViewDidLoad

Hydropathy answered 8/12, 2018 at 6:7 Comment(0)
N
1

Swift 4.2 and Xcode 10 Initialize label before viewDidLoad.

lazy var topLeftLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "TopLeft"
    return label
}()

In viewDidLoad add label to the view and apply constraints.

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(topLeftLabel)
    topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
    topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}
Niobe answered 4/4, 2019 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.