简体   繁体   English

RxSwift无法与UIButton一起使用

[英]RxSwift not working with UIButton

I am working on RxSwift and started creating few basic. 我正在研究RxSwift,并开始创建一些基本的东西。 I have added new button however with rx_tap subscribe not working for button action. 我添加了新按钮,但是rx_tap订阅不能用于按钮操作。 Below is my code, please let me know what I am doing wrong 以下是我的代码,请让我知道我做错了什么

    let button = UIButton(frame: CGRect(x: 10, y: 66, width: 100, height: 21))
    button.backgroundColor = UIColor.redColor()
    button.setTitle("Login", forState: UIControlState.Normal)

    let disposeBag = DisposeBag()
    button.rx_tap
        .subscribe { [weak self] x in
            self!.view.backgroundColor = UIColor.redColor()
    }
    .addDisposableTo(disposeBag)
    self.view.addSubview(button)

Your subscription is cancelled immediately because of the scope of your DisposeBag . 由于您的DisposeBag的范围,您的订阅被立即取消。 It is created, then goes out of scope and immediately deallocated. 它被创建,然后超出范围并立即释放。 You need to retain your bag somewhere. 您需要将包保留在某处。 If you are using a view controller or something like that, you can create a property there and assign it to that. 如果您使用的是视图控制器或类似的控件,则可以在其中创建一个属性并将其分配给该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM