Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift using bindTo for binding Variable<String> to UILabel not working for Swift 3.0 update

Tags:

ios

swift

swift3

I use RxSwift to bind my viewmodel to UILabel and UITexfield. UITextfield ones have no issues converting to Swift 3, just replacing rx_text with rx.text worked.

But not for UILabel. On Swift 2.2, I used:

self.viewModel.shiftNameText.asObservable().bindTo(self.shiftLabel.rx_text).addDisposableTo(self.disposeBag)

For Swift 3, I'm using RxSwift 3.0.0-beta.1 and tried just changing rx_text to rx.text, but it doesn't compile and shows this error "Cannot convert value of type 'AnyObserver<String?>' (aka 'AnyObserver<Optional<String>>') to expected argument type 'Variable<String>".

Does anyone know why and how to make this work? Thanks.

like image 873
JinglesBunny Avatar asked Sep 22 '16 09:09

JinglesBunny


1 Answers

UILabel's rx.text property is of type AnyObserver<String?> so you need to map the value to an optional

self.viewModel.shiftNameText
    .asObservable()
    .map { text -> String? in 
        return Optional(text)
    }
    .bind(to:self.shiftLabel.rx.text)
    .disposed(by:self.disposeBag)

or in short:

self.viewModel.shiftNameText
  .asObservable()
  .map { $0 }
  .bind(to:self.shiftLabel.rx.text)
  .disposed(by:self.disposeBag)

See https://github.com/ReactiveX/RxSwift/issues/875 for other solutions.

like image 166
marcusficner Avatar answered Nov 13 '22 19:11

marcusficner