bkw*_*ero 4 uikit swift combine
@Published我的视图模型中有一个字符串。我想在视图控制器中接收其值的更新,以便我可以更新 UI。
我能够通过使用订阅者成功获取更新sink。这工作正常:
viewModel.$buttonText.sink { [weak self] buttonText in
self?.buttonOutlet.setTitle(buttonText, for: .normal)
}.store(in: &cancellables)
Run Code Online (Sandbox Code Playgroud)
但我正在寻找一种单行方法。更像是您可以使用assign订阅者对 UILabels 执行的操作:
viewModel.$title.assign(to: \.text, on: titleLabel).store(in: &cancellables)
Run Code Online (Sandbox Code Playgroud)
我尝试过buttonOutlet.titleLabel直接访问,但这当然行不通,因为我们无法直接更新文本(UIButton.titleLabel只读)。它还引入了解包属性的问题titleLabel:
viewModel.$buttonText.assign(to: \.!.text, on: buttonOutlet.titleLabel).store(in: &cancellables)
Run Code Online (Sandbox Code Playgroud)
我不知道我是否只是在努力寻找正确的语法,或者这只是暂时的合并的限制。
你可以只写一个扩展:
extension UIButton {
var normalTitleText: String? {
get {
title(for: .normal)
}
set {
setTitle(newValue, for: .normal)
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以获得密钥路径
viewModel.$title.assign(to: \.normalTitleText, on: someButton).store(in: &cancellables)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |