我创建了一个自定义类,它继承自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
}
}
最佳答案
您还必须为选择器设置正确的目标。目前,您正在将目标设置为BlueView
实例,但您希望它是视图控制器。
class BlueView: UIView {
...
func setTapGesture(target: Any?, action: Selector?) {
addGestureRecognizer(UITapGestureRecognizer(target: target, action: action))
}
...
}
&然后您可以使用:
bview.setTapGesture(target: self, action: #selector(handleBlueTap(sender:)))