How To Create, Align And Wrap Label Text Programmatically In Swift iOS App

UIKit.UILabel class is used to create a label in iOS swift source code programmatically. You can change label text, label text color, label background color, label border width, label border color by setting it’s properties. You can also change the label text alignment by change UILabel object’s textAlignment property value t0 NSTextAlignment.left, NSTextAlignment.center or NSTextAlignment.right. You can also change the label text wrap method by setting the label object’s lineBreakMode property. This example will tell you how to create a swift label object programmatically in source code, how to align the label text and how to change the label text line numbers and wrap the label text words. I will also tell you how to make the label text automatically change font size to adapt the label width.

1. Create Swift Label, Align Label Text, Change Text Line Number And Wrap Label Text Programmatically Example.

When the app start, there are one green border label with blue background. When you click the first ‘Change Label Text Alignment’ button, it will change the label text alignment value in NSTextAlignment.left, NSTextAlignment.center, NSTextAlignment.right order. You can see current label text alignment value in the message label tips below the blue label.

create swift label and change label text alignment

When you click the second ‘Change Label Text Line Number & Word Wrap’ button, it will display a long text in the blue label, when you click the button more and more, it will show you the label text line number change and text wrap method change effect.

swift label example change label text line number and word wrap method

When you click the third button ‘Label Text Match Label Size Adaptive’, then the label text will change it’s size to adapt the label width to make it looking fine. You do not need to change the label text size by code.

swift label example make label text match label width automatically

2. Example Source Code.

Below is the example project source files list, the project name is SwiftCreateLabelByCodeExample, you should add three buttons at the screen bottom, and each button is connected with an action event process function. You can read article How To Create A Swift Project In Xcode, How To Display Xcode Library, Assistant Editor, Inspectors Window, How To Connect Storyboard UI Component To ViewController Class Code for more learning.

READ :   How To Use Swift Switch Case Example

swift create label programmatically source code

Then click the ViewController.swift file to edit it and add below source code in it.

//
//  ViewController.swift
//  SwiftCreateLabelByCodeExample
//
//  Created by song zhao on 7/3/19.
//  Copyright © 2019 dev2qa.com. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    let screenWidth = UIScreen.main.bounds.width
    
    let screenHeight = UIScreen.main.bounds.height
    
    // This label is used to display the example text.
    var labelOne : UILabel = UILabel()
    
    // This label is used to display the tips info message.
    var messageLabel : UILabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // First initialize the example label.
        // Create a CGRect object to define the label location and size.
        labelOne.frame = CGRect(x:100, y: screenHeight/2, width: screenWidth - 100, height: 100)
        
        // Set label text.
        labelOne.text = "Hello swift label."
        
        // Make this label locate at screen center.
        labelOne.center = CGPoint(x: screenWidth/2, y: screenHeight/2)
        
        // Set example label corner radius.
        labelOne.layer.cornerRadius = 10
        
        // Set example label border width and color.
        labelOne.layer.borderWidth = 5
        labelOne.layer.borderColor = UIColor.green.cgColor
        
        // Set example label text color and background color.
        labelOne.textColor = UIColor.yellow
        labelOne.backgroundColor = UIColor.blue
        
        // Set example label initial text line numbers and line break mode.
        // Set numberOfLines to 0 means the label text can has any number lines.
        labelOne.numberOfLines = 0
        labelOne.lineBreakMode = .byWordWrapping
        
        
        // Initialize the tips message label.
        messageLabel.frame = CGRect(x: labelOne.frame.origin.x, y: labelOne.frame.origin.y + 100, width: screenWidth, height: 100)
        messageLabel.center = CGPoint(x: screenWidth/2, y: screenHeight/2 + 100)
        
        // Set message label's initial text alignment to center.
        messageLabel.textAlignment = NSTextAlignment.center
        messageLabel.numberOfLines = 0
        
        // Add the two labels to the screen.
        self.view.addSubview(labelOne)
        self.view.addSubview(messageLabel)
    }

    /* This function will be invoked when click button 'Change Label Text Alignment'. */
    @IBAction func changeLabelTextAlignment(_ sender: UIButton) {
        
        labelOne.text = "Hello swift label."
        
        labelOne.adjustsFontSizeToFitWidth = false
        
        let currTextAlignment: NSTextAlignment = labelOne.textAlignment
        
        if(currTextAlignment == NSTextAlignment.left || currTextAlignment == NSTextAlignment.natural){
            
            labelOne.textAlignment = NSTextAlignment.center
            
            messageLabel.text = "Change text alignment to center."
        
        }else if(currTextAlignment == NSTextAlignment.center){
        
            labelOne.textAlignment = NSTextAlignment.right
            
            messageLabel.text = "Change text alignment to right."
        
        }else if(currTextAlignment == NSTextAlignment.right){
        
            labelOne.textAlignment = NSTextAlignment.left
            
            messageLabel.text = "Change text alignment to left."
        
        }
    }

    /* This function will be invoked when click button 'Change Label Text Line Number & Word Wrap'. */
    @IBAction func changeLabelTextLineNumber(_ sender: UIButton) {
        
        labelOne.adjustsFontSizeToFitWidth = false
        
        labelOne.text = "Hello, this is my first iOS application wroten by swift. This is a label example, it will show you how to create a label programmatically in swift, wish you enjoy it."
        
        var currNumberOfLines:Int = labelOne.numberOfLines
        
        labelOne.numberOfLines += 1
        
        if(currNumberOfLines >= 5){
            labelOne.numberOfLines = 0
        }
        
        var currLineBreakModeStr: String = ""
        
        let currLineBreakMode:NSLineBreakMode = labelOne.lineBreakMode
        
        if(currLineBreakMode == .byWordWrapping){
            
            currLineBreakModeStr = "by clipping"
            
            labelOne.lineBreakMode = .byClipping
        
        }else if(currLineBreakMode == .byClipping){
            
            currLineBreakModeStr = "by char wrapping"
            
            labelOne.lineBreakMode = .byCharWrapping
        
        }else if(currLineBreakMode == .byCharWrapping){
            
            currLineBreakModeStr = "by truncating head"
            
            // Because byTruncatingHead, byTruncatingTail and byTruncatingMiddle is very easy to see effect in single line text. So set the numberOfLines to 1.
            labelOne.numberOfLines = 1
            
            labelOne.lineBreakMode = .byTruncatingHead
        
        }else if(currLineBreakMode == .byTruncatingHead){
            
            currLineBreakModeStr = "by truncating tail"
            
            // Because byTruncatingHead, byTruncatingTail and byTruncatingMiddle is very easy to see effect in single line text. So set the numberOfLines to 1.
            labelOne.numberOfLines = 1
            
            labelOne.lineBreakMode = .byTruncatingTail
        
        }else if(currLineBreakMode == .byTruncatingTail){
            
            currLineBreakModeStr = "by truncating middle"
            
            // Because byTruncatingHead, byTruncatingTail and byTruncatingMiddle is very easy to see effect in single line text. So set the numberOfLines to 1.
            labelOne.numberOfLines = 1
            
            labelOne.lineBreakMode = .byTruncatingMiddle
        
        }else if(currLineBreakMode == .byTruncatingMiddle){
            
            currLineBreakModeStr = "by word wrapping"
            
            labelOne.lineBreakMode = .byWordWrapping
        
        }
        
        // Get the label text line number again after change it's value.
        currNumberOfLines = labelOne.numberOfLines
        
        //https://developer.apple.com/documentation/uikit/nslinebreakmode
        
        messageLabel.text = "Current number of lines is \(currNumberOfLines), current line break mode is \(currLineBreakModeStr)"
    }
    
    /* This function will be invoked when click button 'Label Text Match Label Size Adaptive'. */
    @IBAction func matchLabelSizeAdaptive(_ sender: UIButton) {
        
        // Set this UILabel property to make the label text automatically match the label width adaptively.
        labelOne.adjustsFontSizeToFitWidth = true

        // The minimum label text scale percentage. If set this property, the label text font size should not scale to less than 90 percentage of original text font size.
        labelOne.minimumScaleFactor = 0.9
        
    }
    
    
}

References

  1. Swift UILabel Class
  2. NSLineBreakMode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.