Search code examples
swiftuikit

How to create action for UIButton and conner Radius in swift 5


create login button( set title and conner Radius on UI button)

 lazy var loginButton: UIButton = {
    let button = UIButton()
    button.setTitle("Log In", for: .normal)
    button.layer.cornerRadius = 15
    button.backgroundColor = UIColor.red
 
    
    return button
}()

Solution

  • The modern way is to add the action as a UIAction.

    lazy var test: UIButton = {
        let test = UIButton()
        test.translatesAutoresizingMaskIntoConstraints = false
        test.setTitle("See More Answers", for: .normal)
        test.setTitleColor(.systemBlue, for: .normal)
        let action = UIAction { action in
            print("howdy!")
        }
        test.addAction(action, for: .touchUpInside)
        return test
    }()
    

    Nicer syntax can be achieved through an extension, as I demonstrate here.