×

iOS UIButton


What is UIButton ?

UIButton is used to design a button in iPhone Development. It may be custom or default. There are various types of Button available by Default like ...

UIButtonType.custom
UIButtonType.roundedRect
UIButtonType.detailDisclosure
UIButtonType.infoLight
UIButtonType.infoDark
UIButtonType.contactAdd 

Important Methods Mostly Used in UIButton are as follows :-

1) UIButton's setTitle property is used to give title to a Button

 button.setTitle("Button Title here", for: UIControlState.normal)

2) UIButton's setTitleColor property is used to change text Color of a Button

 button .setTitleColor(UIColor.white, for: UIControlState.normal)

3) UIButton's titleLabel.font property is used to give font to a title of a Button

 button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: 1.0)

4) UIButton's addtarget property is used to give target to a Button. When user clicks on a button addTarget property performs user Defined Action.

 button.addTarget(self, action: #selector(self.callButtonClicked), for: UIControlEvents.touchUpInside)
@objc func callButtonClicked()
    {
       print("Call Button Clicked")
    }
    

How to create UIButton with default Types available ?

With the help of buttonWithType Method You can see suggesstions based on UIButton's Types.

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad()
     {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)

       let button = UIButton.init(type: UIButtonType.contactAdd)
        button.frame = CGRect(x:self.view.frame.size.width / 2.0 - 52 , y:80, width: 120 , height: 44)
        self.view.addSubview(button)
        button.setTitle("Call", for: UIControlState.normal)
        button.titleLabel?.textColor = UIColor.white
        button.backgroundColor = UIColor.init(red: 0/255.0, green: 152/255.0, blue: 152/255.0, alpha: 1.0)
        button .setTitleColor(UIColor.white, for: UIControlState.normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: 1.0)
        button.layer.cornerRadius = 2.0
        button.addTarget(self, action: #selector(self.callButtonClicked), for: UIControlEvents.touchUpInside)

     }
 }

4) UIButton's addtarget property is used to give target to a Button. When user clicks on a button addTarget property performs user Defined Action.

 button.addTarget(self, action: #selector(self.callButtonClicked), for: UIControlEvents.touchUpInside)
@objc func callButtonClicked()
    {
       print("Call Button Clicked")
    }