Search code examples
iosswiftuibuttonrx-swiftrx-cocoa

How do I add a control event to a custom button in RxCocoa?


How do I add an .tap method to a custom button, ie. <myCustomButton>.rx.tap in RxSwift/RxCocoa, so that I can bind the tap of the button to an observable.

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: ...)
    }

Solution

  • You don’t need to define it, it has already been defined on UIButton and your custom class inherits that.