Add button programmatically using Autolayouts Swift 5 - iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

27 Apr 2020

Add button programmatically using Autolayouts Swift 5 - iOS

Creating a button using autolayouts is quite simple. In this article, I will show how to add a button programmatically and in addition to that, we will learn about all attributes like color, font, image, etc..


Add button programatically using Autolayouts Swift 5 - iOS


Create UIButton:

First of all, create a new button object of type UIButton, and also set translatesAutoresizingMaskIntoConstraints to false. Then give the auto layouts as follow:

let swiftButton = UIButton()
swiftButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(swiftButton)
swiftButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
swiftButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
swiftButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
swiftButton.heightAnchor.constraint(equalToConstant: 50).isActive = true


Add a title to Button:

swiftButton.setTitle("Thunder", for: .normal)

Add a title to Button:

Change button title Font & Size:

swiftButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)


Change button title Font & Size:

Change Button background color:

swiftButton.backgroundColor = UIColor.white

Change Button background color:

Change Button title color:

swiftButton.setTitleColor(UIColor.black, for: .normal)

Change Button title color:

Add image to button:

swiftButton.setImage(UIImage(named: "thunder"), for: .normal)

Add image to button:

Change image color in Button:

swiftButton.tintColor = UIColor.red


 Change image color in Button:

Space between button image and title:


swiftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)

Space between button image and title:

Add tap action on Button:

swiftButton.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)



@objc func buttonTapped(sender: UIButton) {

    print("Button tapped")

}

Change Button title color On Tapped or Selected:

swiftButton.setTitleColor(UIColor.green, for: .highlighted)

Change Button title color On Tapped or Selected:
 

Conclusion:

As a result, we learn how to create a button programmatically & setting up all button properties.



No comments:

Post a Comment

Post Top Ad