【问题标题】:Add a rx.value to my CustomView将 rx.value 添加到我的 CustomView
【发布时间】:2018-06-21 13:44:36
【问题描述】:

假设我有一个带有值的 CustomView。 我想使用 rx.value (Observable) 向世界公开该值,而不是通过值 (Int) 访问它。

final class CustomView: UIView {
   var value: Int = 0
   ...
}

我从 UIStepper+Rx 复制了这个:

extension Reactive where Base: CustomView {

    var value: ControlProperty<Int> {
        return base.rx.controlProperty(editingEvents: [.allEditingEvents, .valueChanged],
            getter: { customView in
                customView.currentValue
        }, setter: { customView, value in
            customView.currentValue = value
        }
        )
    }

}

final class CustomView: UIControl {

    fileprivate var currentValue = 1 {
        didSet {
            checkButtonState()
            valueLabel.text = currentValue.description
        }
    }

   // inside i set currentValue = 3
}

但是 customView.rx.value 不会发出任何值

【问题讨论】:

  • 你能帮我解决这个问题吗? " 'Reactive' 类型的值没有成员 'controlProperty' "

标签: ios swift rx-swift rx-cocoa


【解决方案1】:

缺少的是,您需要在UIControl 上发送操作。检查下一个示例:

class CustomView: UIControl {
    var value: Int = 0 {
        didSet { sendActions(for: .valueChanged) } // You are missing this part
    }
}

extension Reactive where Base: CustomView {

    var value: ControlProperty<Int> {
        return base.rx.controlProperty(editingEvents: UIControlEvents.valueChanged,
                                       getter: { customView in
                                        return customView.value },
                                       setter: { (customView, newValue) in
                                        customView.value = newValue})
    }

}

【讨论】:

  • 你能帮我解决这个问题吗? “'Reactive' 类型的值没有成员 'controlProperty'”
  • 你必须import RxCocoa
【解决方案2】:

我认为您想使用主题,无论是发布主题还是变量。

一个 PublishSubject 以一个空序列开始,并且只向其订阅者发出新的 Next 事件。变量允许在开始时设置初始值并将最新或初始值重播给订阅者。保证变量不会失败,它不会也不会发出错误。 本教程帮助https://medium.com/@dkhuong291/rxswift-subjects-part1-publishsubjects-103ff6b06932

所以你需要像这样为你的主题设置价值:

 var myValue = PublishSubject<Int>()
 ...
 myValue.onNext(2)

 var myValue = Variable<Int>(0)
 ...
 myValue.value = 2

然后订阅它:

var disposeBag = DisposeBag()
myValue.asObservable()
    .subscribe({
        print($0)
    }).disposed(by: disposebag) 

此外,您可能只想使用字符串主题将值绑定到您的 UILabel。

var myValue = PublishSubject<String>()
...
myValue.onNext("\(4)")
...
func viewDidLoad() {
     super.viewDidLoad()
     myValue.asObservable().bind(to: valueLabel.text)
}

或者,假设您想通过 rx.value 设置您的值。您需要使用 RxCocoa 创建一个自定义视图的 DelegateProxy 类。这与为您的 CustomView 创建一个委托相同,您可以在其中委托您的属性,方法是在您想要的任何地方设置它们的值并通过 customView.rx 收听它们...

我上个月在 What delegate cant do than Reactive? 上发布了一些内容。 它真的帮助我轻松控制我的自定义视图属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多