ios - UITapGestureRecognizer 不适用于自定义视图类
问题描述
UITapGestureRecognizer
在代码 1中工作得很好。tapAction
按预期调用。但是它在代码 2中不起作用。有人可以告诉我代码 2有什么问题吗?
代码 1:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
myView.backgroundColor = .red
myView.addGestureRecognizer( UITapGestureRecognizer(target:self,action:#selector(self.tapAction)) )
self.view.addSubview(myView)
}
@objc func tapAction() {
print("tapped")
}
}
代码 2:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myView = MyView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
self.view.addSubview(myView)
}
}
class MyView : UIView {
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView(){
let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
myView.backgroundColor = .red
myView.addGestureRecognizer(UITapGestureRecognizer(target:self,action:#selector(self.doSomethingOnTap)))
addSubview(myView)
}
@objc func doSomethingOnTap() {
print("tapped")
}
}
解决方案
您正在创建一个在这种特殊情况下超出父边界的子视图,因为视图主视图具有 100 高度和 100 宽度,并且子视图放置在 x: 100 和 y: 100 处,从而定位在确切的末尾的父母。
您在其中创建的子视图initView
应该有(x: 0, y: 0)
来源。
推荐阅读
- python - BST广度优先遍历,包括删除节点
- php - Laravel:1215 无法添加外键约束 - 迁移时
- python - 用python从c源代码文件中提取函数代码
- android - 如何阻止android通知重复自身
- php - 使用 PHP PDO / 函数从数据库中获取指定行
- python - 如果有效,但 Else 不循环会是更好的选择吗?(Python)
- android - 我的应用程序不受 GDPR 暂停的影响吗?
- angular - Angular 7/NgRX 初始化时的后端认证(初始化效果)
- node.js - 我的虚拟专用服务器似乎没有端口
- spring-boot - 如何将“requestParameters”记录为数组