ios-swift3中的选择器

为什么这在Swift 3中不起作用? 它在运行时崩溃说:

'-[my_app_name.displayOtherAppsCtrl tap:]:无法识别的选择器已发送 实例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")
}
}
Chris asked 2020-06-18T10:16:07Z
4个解决方案
124 votes

func tap(_ gestureRecognizer: UITapGestureRecognizer)现在应该写为#selector(tap(_:))

另外,根据新的Swift API指南,您应将tap声明为func tap(_ gestureRecognizer: UITapGestureRecognizer),在这种情况下,您的选择器将变为#selector(tap(_:))

jjatie answered 2020-06-18T10:16:27Z
19 votes

在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")
}
Neen answered 2020-06-18T10:16:47Z
2 votes

Swift 3带有新语法,因此不是使用Selector(“ tap:”),而是使用#selector(tap(gestureReconizer :))

Zeeshan answered 2020-06-18T10:17:07Z
0 votes

斯威夫特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--")
}
GeekMeng answered 2020-06-18T10:17:27Z
translate from https://stackoverflow.com:/questions/38038418/selector-in-swift3