Swift 3之前 事件的监听很简单,直接"btnClick"就可以 ,但是这样存在一定的问题,以字符串的形式进行监听,如果字符串拼写错误,编译器是编译不出来的!
btn.addTarget(self, action: "sender", for: .touchUpInside)
所以Swift 3 苹果修复了这样的bug,采用#selector()进行事件的监听
btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
Swift 3 按钮事件监听完整代码如下 :
import UIKit
class ViewController: UIViewController {
var btn:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
btn.frame = CGRect(x: 0, y: 0, width: 100, height: 50)
btn.center = view.center
btn.setTitle("点我啊", for: .normal)
btn.setTitle("上当了吧", for: .selected)
btn.backgroundColor = UIColor.orange
btn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
view.addSubview(btn)
}
}
extension ViewController{
@objc fileprivate func btnClick(sender : UIButton) {
sender.isSelected = !sender.isSelected
}
}
网友评论