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 the 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 the font size to adapt the label width.

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

Browse the URL https://youtu.be/s_OQ5z44wK0 to watch if you can not see it in the above video.

  1. When the app starts, there is one green border label with blue background.
  2. 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.
  3. You can see the current label text alignment value in the message label tips below the blue label.

The youtube URL for the above demo video is https://youtu.be/yllhJPq40kU.

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

If you can not watch the above demo video, you can watch it on URL https://youtu.be/J7wFeyCXq-U.

  1. 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 look fine.
  2. You do not need to change the label text size by code.

2. Example Source Code.

  1. 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.
  2. You can read the 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.
  3. Then click the ViewController.swift file to edit it and add the below source code in it.
    //
    //  ViewController.swift
    //  SwiftCreateLabelByCodeExample
    //
    //  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 are very easy to see an 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 are very easy to see the 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 are very easy to see an 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 percent of the original text font size.
            labelOne.minimumScaleFactor = 0.9
            
        }
        
        
    }
    

References

  1. Swift UILabel Class
  2. NSLineBreakMode

Leave a Comment

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.