Selector in swift3

后端 未结 4 1888
悲&欢浪女
悲&欢浪女 2020-11-30 03:23

Why doesn\'t this work in swift 3 ? It crashes at runtime saying:

\'-[my_app_name.displayOtherAppsCtrl tap:]: unrecognized selector sent to instanc

相关标签:
4条回答
  • 2020-11-30 04:24

    Swift 3:

    class MYPTempController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
            view.addSubview(btn)
            btn.addTarget(self, action: #selector(MYPTempController.btnClick), for: .touchUpInside)
        }
        @objc fileprivate func btnClick() {
            print("--click--")
        }
    }
    

    //带参数
    btn.addTarget(self, action: #selector(MYPTempController.btnClick(_:)), for: .touchUpInside)
    //监听方法
    func btnClick(_ sender: UIButton) {
        print("--click--")
    }
    
    0 讨论(0)
  • 2020-11-30 04:25

    Selector("tap:") should now be written as #selector(tap(gestureReconizer:))

    Also, you should declare tap as func tap(_ gestureRecognizer: UITapGestureRecognizer) as per the new Swift API Guidelines in which case your selector would then become #selector(tap(_:)).

    0 讨论(0)
  • 2020-11-30 04:26

    Swift 3 came with new syntax so instead of using Selector("tap:"), #selector(tap(gestureReconizer:)) is

    0 讨论(0)
  • 2020-11-30 04:29

    In Swift 3 it works like this:

    @IBOutlet var myView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))
    
        myView.addGestureRecognizer(tap)
    }
    
    func handleTap() {
        print("tapped")
    }
    
    0 讨论(0)
提交回复
热议问题