Reactivecocoa binding UIButton's title

时间:2016-04-25 09:31:49

标签: ios uibutton reactive-cocoa

RAC(self.balanceLabel,text) = RACObserve(self.viewModel, balance); // balanceLabel is a UILabel,that is ofcourse work
RAC(self.supplierNameButton.titleLabel.text)  = RACObserve(self.viewModel, supplierName); // that is not work,i think this is I don't use the - setTitle:forState: method

My question is:how can i use Reactivecocoa binding the view model's supplier to the UIButon text of its UIControlStateNormal

2 个答案:

答案 0 :(得分:1)

不幸的是,绑定仅适用于属性,而按钮的文本只能使用setTitle:forState方法进行更新。

但是有一种解决方法:您可以使用rac_liftSelector:withSignalsFromArray方法,这在您不想使用订阅时很有用(以及weakify / strongify):< / p>

[self.supplierNameButtonButton rac_liftSelector:@selector(setTitle:forState:) withSignalsFromArray:@[RACObserve(self.viewModel, supplierName), [RACSignal return:@(UIControlStateNormal)]]];

答案 1 :(得分:0)

标题需要在订阅栏中更新

@weakify(self)
[RACObserve(self.viewModel, supplierName)
    subscribeNext:^(NSString *supplierName) {
        @strongify(self)
        [self.supplierNameButton setTitle:supplierName forState:UIControlStateNormal];
    }];

将订阅移至UIButton上的类别方法

 - (void)setTitleSignal:(RACSignal *)titleSignal forState:(UIControlState)state {
    @weakify(self)
    [titleSignal subscribeNext:^(NSString *title) {
        @strongify(self)
        [self setTitle:title forState:state];
    }];

}

绑定可以表达得更清晰

[self.supplierNameButton setTitleSignal:RACObserve(self.viewMode, supplierName) forState:UIControlStateNormal];