ios RxSwift 使用 bindTo 将 Variable<String> 绑定到 UILabel 不适用于 Swift 3.0 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39635262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:19:53  来源:igfitidea点击:

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

iosswiftswift3

提问by JinglesBunny

I use RxSwiftto bind my viewmodelto UILabeland UITexfield. UITextfieldones have no issues converting to Swift 3, just replacing rx_textwith rx.textworked.

RxSwift用来绑定我的viewmodeltoUILabelUITexfieldUITextfield转换为 没有问题Swift 3,只需替换rx_textrx.text工作。

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

但不是为了UILabel. 在Swift 2.2,我用过:

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

For Swift 3, I'm using RxSwift3.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>".

对于Swift 3,我正在使用RxSwift3.0.0-beta.1 并尝试将 rx_text 更改为rx.text,但它无法编译并显示此错误“无法转换类型的值”AnyObserver<String?>' (aka 'AnyObserver<Optional<String>>') to expected argument type 'Variable<String>".

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

有谁知道为什么以及如何使这项工作?谢谢。

回答by marcusficner

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

UILabelrx.text属性属于类型,AnyObserver<String?>因此您需要将该值映射到可选的

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 { ##代码## }
  .bind(to:self.shiftLabel.rx.text)
  .disposed(by:self.disposeBag)

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

有关其他解决方案,请参阅https://github.com/ReactiveX/RxSwift/issues/875