How To Add Text Margin or Padding In Swift UIButton

This example will show you how to create a swift button programmatically and how to set it’s text, text color, border width, border color, border corner radius and most important is how to add text margin / padding between the text and button border etc.

Below is the example demo video. By default the button has green border, blue text, and light gray background. You can see there are margins / paddings between button border and button text. When you touch the button, the text color will change to red. And the button border color will change to blue.

If you can not watch the above video, you can see it on URL https://youtu.be/V6lSgj9kC08

Below is the source code. You should first create a Xcode project use Single View App template ( How To Create A Swift Project In Xcode ). Then just need to edit ViewController.swift file use below source code.

//
//  ViewController.swift
//  iOSButtonAddMarginExample
//
//  Created by song zhao on 12/12/19.
//  Copyright © 2019 dev2qa.com. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var btn:UIButton? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create a UIButton object.
        btn = UIButton()
        
        // Set button title.
        btn?.setTitle("Click Me", for: UIControl.State.normal)
        
        // Set button background color.
        btn?.backgroundColor = UIColor.lightGray
        
        // Set button border width.
        btn?.layer.borderWidth = 3
        
        // Set button border color and transparence value.
        btn?.layer.borderColor = CGColor(srgbRed: CGFloat(0), green: CGFloat(255), blue: CGFloat(0), alpha: CGFloat(1))
        
        // Set button border corner radius.
        btn?.layer.cornerRadius = 10
        
        // Set button title line break mode to by word wrapping.
        btn?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
        
        // Set button title color for normal state.
        btn?.setTitleColor(UIColor.blue, for: UIControl.State.normal)
        
        // Set button title color for highlighted state.
        btn?.setTitleColor(UIColor.red, for: UIControl.State.highlighted)
        
        // Set button title font to system bold font, and the font size is 20.
        btn?.titleLabel?.font = UIFont.boldSystemFont(ofSize: CGFloat(20))
        
        // Set button's translatesAutoresizingMaskIntoConstraints property value to false, then you can change it's layout constraints programmatically later.
        btn?.translatesAutoresizingMaskIntoConstraints = false
        
        // Add the button object as the sub view of app main view.
        self.view.addSubview(btn!)
        
        // Set button top layout constraint.
        let btnTopAnchor = btn?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100)
        btnTopAnchor!.isActive = true
        
        // Layout this button at horizontal center.
        let btnCenterXAnchor = btn!.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
        btnCenterXAnchor.isActive = true
        
        // Below code will add padding / margin between button title text and button border.
        // Layout this button's width as the device width minus 300.
        let btnWidthAnchor = btn!.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -300)
        btnWidthAnchor.isActive = true
        
        // Add button touch down event process function.
        btn?.addTarget(self, action: #selector(processBtnEvent), for: UIControl.Event.touchDown)
        
    }


    /* This function will process button touch down event. */
    @objc func processBtnEvent(src:UIButton, event:UIControl.Event){
                
        print("button press down.")
        
        let borderColor1 = CGColor(srgbRed: CGFloat(0), green: CGFloat(0), blue: CGFloat(255), alpha: CGFloat(1))
        
        let borderColor2 = CGColor(srgbRed: CGFloat(0), green: CGFloat(255), blue: CGFloat(0), alpha: CGFloat(1))
        
        // Change the border color by it's original border color.
        if(src.layer.borderColor == borderColor1)
        {
            src.layer.borderColor = borderColor2
        }else{
            src.layer.borderColor = borderColor1
        }
    }
}

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.