首页 > 解决方案 > 将选择器从 UIViewController 传递给 UIView

问题描述

我创建了一个继承自 UIView 的自定义类,BlueView. 我的 UIViewController 中有一个方法,我想BlueView在用户点击时调用它。但是,每当我点击 时,我的程序就会崩溃,但BlueView出现以下异常:

2019-09-15 23:06:14.960704-0400 DoubleViewApp[2418:70709] -[DoubleViewApp.BlueView handleBlueTapWithSender:]: unrecognized selector sent to instance 0x7f820cd06790

界面视图:

import UIKit

class BlueView: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)
    createSubview()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    createSubview()
  }

  func createSubview() {
    print("createSubview from BlueView")
    backgroundColor = .blue

    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
    addGestureRecognizer(tap)
  }

  func setTapGesture(action: Selector?) {
    let tap = UITapGestureRecognizer(target: self, action: action)
    addGestureRecognizer(tap)
  }

  @objc func handleTap(sender: UITapGestureRecognizer? = nil) {
    print("NO! DO NOT TAP THE BLUE SQUARE.")

  }

}

视图控制器:

import UIKit

class ViewController: UIViewController {


  override func viewDidLoad() {
    super.viewDidLoad()
    print("Hello World")
    // Do any additional setup after loading the view.
    let bview = BlueView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    let rview = RedView(frame: CGRect(x: 0, y: 300, width: 300, height: 300))
    view.addSubview(bview)
    view.addSubview(rview)

    bview.setTapGesture(action: #selector(handleBlueTap(sender:)))
  }


  @objc func handleBlueTap(sender: UITapGestureRecognizer? = nil) {
    print("This is a funny message.")
    //Todo: Present new ViewController
  }
}

标签: iosswift

解决方案


您还必须为选择器设置正确的目标。目前,您将目标设置为BlueView实例,但您希望它成为视图控制器。

class BlueView: UIView {

    ...

    func setTapGesture(target: Any?, action: Selector?) {
        addGestureRecognizer(UITapGestureRecognizer(target: target, action: action))
    }

    ...

}

& 然后你可以使用:

bview.setTapGesture(target: self, action: #selector(handleBlueTap(sender:)))

推荐阅读