select器在swift3

为什么这不能在迅速3? 它在运行时崩溃说:

' – [my_app_name.displayOtherAppsCtrl tap:]:无法识别的select器发送到实例0x17eceb70'

override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.register(ImageCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. let lpgr = UITapGestureRecognizer(target: self, action: Selector("tap:")) lpgr.delegate = self collectionView?.addGestureRecognizer(lpgr) } func tap(gestureReconizer: UITapGestureRecognizer) { if gestureReconizer.state != UIGestureRecognizerState.ended { return } let p = gestureReconizer.location(in: self.collectionView) let indexPath = self.collectionView?.indexPathForItem(at: p) if let index = indexPath { //var cell = self.collectionView?.cellForItem(at: index) // do stuff with your cell, for example print the indexPath print(index.row) } else { print("Could not find index path") } } 

Selector("tap:")现在应该被写为#selector(tap(gestureReconizer:)) Selector("tap:") #selector(tap(gestureReconizer:))

此外,你应该声明作为func tap(_ gestureRecognizer: UITapGestureRecognizer)按照新的Swift API指南,在这种情况下,你的select器将成为#selector(tap(_:))select器#selector(tap(_:))

在Swift 3中,它的工作原理是这样的:

 @IBOutlet var myView: UIView! override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap)) myView.addGestureRecognizer(tap) } func handleTap() { print("tapped") } 

Swift 3带有新的语法,所以不是使用Selector(“tap:”),#selector(tap(gestureReconizer :))是

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