search

Home  >  Q&A  >  body text

ios - swift如何对按钮添加点击触发事件,我这样写没有用啊

PHP中文网PHP中文网2808 days ago343

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 17:50:28

    Which version of swift is yours? If it is 2.2:

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

    If it is a version before 2.2:

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

    I haven’t tested the specific syntax, but it should be roughly like this.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:50:28

    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")
        }
    
    }

    reply
    0
  • Cancelreply