ios - 自定义 UIView addTarget 或 RxCocoa 订阅中的 UIButton 不起作用
问题描述
我有一个名为 的 UIView 子类,它创建并保存对 a和 a对象AppChooseField
的强引用。我在我的内部创建了一个,将其添加到 VC 的视图中,然后点击 AppChooseField 实例内的一个按钮,但该按钮不起作用,没有任何反应,没有调用方法。UILabel
UIButton
AppChooseField
UIViewController
flipHelp
class AppChooseField: UIView {
private var button: UIButton!
private var label: UILabel!
private var disposeBag = DisposeBag()
convenience init(frame: CGRect, text: String, description: String) {
self.init(frame: frame)
// Factory method for creating a UIButton, which being displayed without problems
self.button = UIButton.create(text: text, ...)
// Factory for creating a UILabel, which being displayed without problems
self.label = UILabel.create(text: description, ...)
// After that, setting constraints, adding subviews etc.
self.addSubview(self.label)
self.addSubview(self.button)
setConstraints()
// ***** Not calling flipHelp when button tapped
self.button!.rx.tap.subscribe(onNext: { [unowned self] in
self.flipHelp()
}).disposed(by: disposeBag)
// ***** Also not calling flip when button tapped
self.button!.addTarget(self, action: #selector(flipHelp), for: .touchUpInside)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.flipHelp() // flipHelp is called successfully.
}
}
@objc func flipHelp() {
print("Help!")
}
}
我希望我的例子足以传达问题。有什么我不明白的吗?是否有一些我遗漏的与内存相关的问题?
谢谢!
解决方案
事件没有响应,我理解有两种情况
1.userInteractionEnabled = NO
2.子视图超出父视图范围
我没有看到按钮的布局,你的约束可能有点问题,你可以改成:
self.addSubview(self.label)
self.addSubview(self.button)
setConstraints()
推荐阅读
- javascript - 在Angular中单击编辑时内联编辑表格行
- java - 将 txt 文件的重复列添加到 Java 中的列表中
- excel - How to just identify (and not remove) duplicates in excel column?
- java - 如何在 GSON 中支持多语言(在 Json 和 Java 对象之间)?
- laravel - Laravel Artisan 命令的 PHPUnit 测试,无需在内部实例中调用外部 API(依赖注入)
- c# - SSIS中for循环下的脚本任务每个容器都需要大量时间才能完成
- java - 如何在本地保存字符串然后以编程方式更新它们?
- c++ - 在不安装 Outlook 的情况下使用自定义简单 Mapi DLL
- java - Kotlin:重载分辨率歧义
- c# - 在实体框架中删除实体的正确方法是什么?