UIButton programmatically in Swift

  1. How to set Image in UIButton ?
  2. How to set UIButton border ?
  3. How to create gradient UIButton ?
  4. How to add target to UIButton ?

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)

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

How to create gradient UIButton ?

//Setting gradient color of UIButton

let gradientLayer = CAGradientLayer()

How to add target to UIButton ?

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

Thank you. Happy Coding!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nitish Kumar

Nitish Kumar

20 Followers

I developed and maintain applications aimed at a range of iOS devices including mobile phones and tablet computers.