Home > Back-end >  How to create action for UIButton in UIKit
How to create action for UIButton in UIKit

Time:08-22

I just created a UIButton and I want to do some action when I click on it:

lazy var test: UIButton = {
    let test = UIButton()
    test.translatesAutoresizingMaskIntoConstraints = false
    test.setTitle("See More Answers", for: .normal)
    test.setTitleColor(.systemBlue, for: .normal)

    return seeMoreBtn
}()

CodePudding user response:

 lazy var test: UIButton = {
    let test = UIButton()
    test.translatesAutoresizingMaskIntoConstraints = false
    test.setTitle("See More Answers", for: .normal)
    test.setTitleColor(.systemBlue, for: .normal)
    test.addTarget(self, action: #selector(self.buttonPressedAction), for: .touchUpInside) // add target

    return seeMoreBtn
}()
@objc func buttonPressedAction() {
    //This function will get called when u press the button.
    //include here what u want to do.
 }

CodePudding user response:

@objc func buttonAction() {
    print("Button Tapped")
}

test.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
  • Related