swift3中的选择器

Chr*_*ris 47 selector 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")
}
}
Run Code Online (Sandbox Code Playgroud)

jja*_*tie 124

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

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

  • 你必须这样写:`#selector(ClassName.MethodName)`否则你可能有关于objc选择器的错误. (5认同)

小智 19

在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")
}
Run Code Online (Sandbox Code Playgroud)

  • 这很好,因为它表明你必须在方法中初始化UITapGestureRecognizer ...我遇到了重大问题,因为我(尽管是愚蠢地)声明并初始化文件顶部的点击.接下来调试信息很差,需要花费很长时间才能解决:S ...需要注意的是,如果你把这个函数设为私有,你似乎必须在"私有函数..."之前添加@objc. (2认同)