1

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: ...)
    }
Samuel Kith
  • 109
  • 12

3 Answers3

0

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

Iman Nia
  • 2,255
  • 2
  • 15
  • 35
  • I can't do that. I have tried and tap method is not there. In addition, I am creating the UICircularButton in a custom view and loading it in my ViewController, but this should not be the cause right? – Samuel Kith Jun 13 '19 at 07:26
  • @SamuelKith right look like you found it, good luck by the way – Iman Nia Jun 13 '19 at 08:39
0

You could assign the binding inside UIActionButton declaration like so

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")
}()
Eternal Black
  • 259
  • 2
  • 15
0

I have found out the issue, it is my mistake, the button is nested inside one more layer and due to poor naming, I have missed that out.

Samuel Kith
  • 109
  • 12