如何在RxCocoa中将控件事件添加到自定义按钮?

时间:2019-06-13 07:08:29

标签: ios swift uibutton rx-swift rx-cocoa

如何将.tap方法添加到自定义按钮,即<myCustomButton>.rx.tap在RxSwift / RxCocoa中,因此我可以将按钮的点击绑定到可观察对象。

CircularButton.swift

class UICircularButton: UIButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        clipsToBounds = true
        subviews.first?.contentMode = .center

        let layer: CALayer = self.layer
        layer.cornerRadius = self.frame.size.width / 2
        layer.masksToBounds = true
    }
}

ViewController.swift

let transferButton: UIActionButton = {
        let button = UICircularButton(type: .system)
        button.setBackgroundImage(#imageLiteral(resourceName: "transfer"), for: .normal)
        button.backgroundColor = Colors.trueGreen
        return UIActionButton(button: button, actionLabel: "Transfer")
    }()

// Question
func configureBinding() {
        // How do I do this
        transferButton.rx.tap
            .bind(to: ...)
            .dispose(by: ...)
    }

3 个答案:

答案 0 :(得分:2)

您不需要定义它,它已经在UIButton上定义了,您的自定义类继承了它。

答案 1 :(得分:1)

我发现了这个问题,这是我的错误,该按钮嵌套在另外一层中,由于命名不当,我错过了这一点。

答案 2 :(得分:0)

您可以像这样在UIActionButton声明中分配绑定

let transferButton: UIActionButton = {
    let button = UICircularButton(type: .system)
    button.setBackgroundImage(#imageLiteral(resourceName: "transfer"), for: .normal)
    button.backgroundColor = Colors.trueGreen
    button.rx.tap.bind {
        // My code or function call
    }.disposed(by: self.disposeBag)
    return UIActionButton(button: button, actionLabel: "Transfer")
}()