首页 > 解决方案 > 自定义 UIView addTarget 或 RxCocoa 订阅中的 UIButton 不起作用

问题描述

我有一个名为 的 UIView 子类,它创建并保存对 a和 a对象AppChooseField的强引用。我在我的内部创建了一个,将其添加到 VC 的视图中,然后点击 AppChooseField 实例内的一个按钮,但该按钮不起作用,没有任何反应,没有调用方法UILabelUIButtonAppChooseFieldUIViewControllerflipHelp

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!")
    }
}

我希望我的例子足以传达问题。有什么我不明白的吗?是否有一些我遗漏的与内存相关的问题?

谢谢!

标签: iosswift

解决方案


事件没有响应,我理解有两种情况

1.userInteractionEnabled = NO

2.子视图超出父视图范围

我没有看到按钮的布局,你的约束可能有点问题,你可以改成:

self.addSubview(self.label)
self.addSubview(self.button)
setConstraints()

推荐阅读