UIButton programmatically in Swift
In swift, UIButton is created by two methods, first one is outlet method and second is programmatically.
In this story, we will create a programmatic UIButton and few more things for button i.e. given below.
- How to create button Programmatically?
- How to set Image in UIButton ?
- How to set UIButton border ?
- How to create gradient UIButton ?
- How to add target to UIButton ?
Let’s start with first point,
How to create button Programmatically ?
//Creating UIButton
let newButton = UIButton()
//Creating frame for UIButton
newButton.frame = CGRect.init(x: self.view.frame.width/3.5, y: self.view.frame.height/2, width: 180, height: 50)
//Setting Title for UIButton
newButton.setTitle(“Swift”, for: .normal)
//Setting Title color for UIButton
newButton.setTitleColor(.white, for: .normal)
//Setting background color for UIButton
newButton.backgroundColor = .red
//adding UIButton to view
view.addSubview(newButton)
The whole code will like given below:
How to set Image in UIButton ?
//Setting Image for UIButton
newButton.setImage(.strokedCheckmark, for: .normal)
How to set UIButton border ?
//Setting border of UIButton
newButton.layer.borderColor = UIColor.black.cgColor
newButton.layer.borderWidth = 1.5
newButton.layer.cornerRadius = 5
How to create gradient UIButton ?
//Setting gradient color of UIButton
let gradientLayer = CAGradientLayer()
gradientLayer.frame = newButton.bounds
let topGradientColor = UIColor.red
let bottomGradientColor = UIColor.orange
gradientLayer.colors = [topGradientColor.cgColor, bottomGradientColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.5, y:1.0)
gradientLayer.locations = [0.0, 1.0]
newButton.layer.insertSublayer(gradientLayer, at: 0)
How to add target to UIButton ?
newButton.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
@objc func buttonTapped(sender : UIButton) {
//Write button action here
print(“button clicked”)
}
Thank you. Happy Coding!!