Как добавить событие управления к пользовательской кнопке в RxCocoa?

Как добавить метод .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: ...)
    }

person Samuel Kith    schedule 13.06.2019    source источник


Ответы (3)


Вам не нужно его определять, он уже был определен в UIButton, и ваш пользовательский класс наследует его.

person Iman    schedule 13.06.2019
comment
Я не могу этого сделать. Я пробовал, и метода нажатия там нет. Кроме того, я создаю UICircularButton в пользовательском представлении и загружаю его в свой ViewController, но это не должно быть причиной, верно? - person Samuel Kith; 13.06.2019
comment
@SamuelKith похоже, ты нашел это, удачи, кстати - person Iman; 13.06.2019

Вы можете назначить привязку внутри объявления 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")
}()
person Eternal Black    schedule 13.06.2019

Я обнаружил проблему, это моя ошибка, кнопка вложена в еще один слой, и из-за плохого именования я это пропустил.

person Samuel Kith    schedule 13.06.2019