DWQA QuestionsCategory: ServerIt's useless for me to write how swift adds click trigger events to buttons
codeBrother asked 3 weeks ago

It's useless for me to write how swift adds click trigger events to buttons

2 Answers
Best Answer
Unsolved answered 3 weeks ago

What is your swift version? If 2.2:

button.addTarget(self, action: #selector(buttonTapped), forControlEvents: .TouchUpInside)

For versions prior to 2.2:

button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)

I didn’t test specific grammar, but it should be.

codeBrother replied 3 weeks ago

All right. I need that number. I’ll get a hint when I’m done… I’m drunk

Havthgem answered 3 weeks ago

Refer to the following code

import UIKit

class BaseViewController: UIViewController {

    let button = UIButton(frame: CGRect(x: 100, y: 150, width: 120, height: 50))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.backgroundColor = UIColor.blueColor()
        button.setImage(UIImage(named: "2.jpg"), forState: .Highlighted)
        button.addTarget(self, action: #selector(buttonTapped(_:)), forControlEvents: .TouchUpInside)
        view.addSubview(button)
    }
    
    func buttonTapped(sender: UIButton) {
        print("hello")
    }

}