ios - Swift:视图控制器触摸事件中的自定义 UIButton 类未触发?
问题描述
我这样创建了一个自定义UIButton
类:
class CustomButton: UIButton
{
required init(frame: CGRect, title: String, alignment: NSTextAlignment)
{
super.init(frame: frame)
// Set properties
// self.addTarget(self,
// action: #selector(touchCancel),
// for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
// @objc fileprivate func touchCancel()
// {
// print("TOUCHED")
// }
}
在我的 mainUIViewController
中,我有以下实现:
class MainViewController: UIViewController
{
fileprivate var customBtn: CustomButton {
let frame = CGRect(x: 48.0,
y: 177.0,
width: 80.0,
height: 40.0)
let custom = CustomButton(frame: frame,
title: "Test",
alignment: NSTextAlignment.right)
return custom
}
override func viewDidLoad()
{
super.viewDidLoad()
view.addSubView(customBtn)
customBtn.addTarget(self,
action: #selector(touchCancel),
for: .touchUpInside)
}
@objc public func touchCancel()
{
print("TOUCHED")
}
}
但是,customBtn
在我的主目录中添加目标UIViewController
不会被触发。CustomButton
如带有注释掉代码的类中所示,我可以在那里添加一个目标,它确实会被触发。
我只是想知道为什么不能使用另一个类中定义的函数作为目标添加到自定义UIButton
?....或者我的实现不正确?
谢谢!
解决方案
您可能需要一个闭包而不是计算属性
lazy var customBtn: CustomButton = {
let frame = CGRect(x: 48.0, y: 177.0, width: 80.0, height: 40.0)
let custom = CustomButton(frame: frame, title: "Test",alignment: NSTextAlignment.right)
return custom
}()
这里里面MainViewController
customBtn.addTarget(self,
action: #selector(touchCancel),
for: .touchUpInside)
您将目标添加到新创建的实例而不是添加为子视图的实例,这是您的实现(计算属性)和闭包之间的主要区别
推荐阅读
- flutter - 如何使用颤振安排本地通知
- java - 尝试使用 ProcessBuilder 从命令行启动服务器
- php - 如何使用 PHP Profiler 跟踪 Mysql 慢查询日志文件条目
- computer-science - 在特定时间后仅更新数组中特定项目的最佳方法是什么?
- java - JLabel 的文本在 hitbox 的中间
- python - 在哪里添加while循环以使最小值和最大值正常工作
- git - 如何使用 AWS Code Deploy 和 AWS Code Pipeline 一次部署多个 git 存储库?
- python - 如何在函数 root.destroy 之后运行代码
- activerecord - 使用关系通过和比较运算符时,Yii2 对父模型表的别名
- android - shouldShowRequestPermissionRationale 方法的工作