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..
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)
Change button title Font & Size:
swiftButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
Change Button background color:
swiftButton.backgroundColor = UIColor.white
Change Button title color:
swiftButton.setTitleColor(UIColor.black, for: .normal)
Add image to button:
swiftButton.setImage(UIImage(named: "thunder"), for: .normal)
Change image color in Button:
swiftButton.tintColor = UIColor.red
Space between button image and title:
swiftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
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)