gpt4 book ai didi

Swift结合问题与UILabel订阅

转载 作者:行者123 更新时间:2023-12-04 10:31:28 26 4
gpt4 key购买 nike

import UIKit
import Combine

class ViewController: UIViewController {

@IBOutlet weak var allowMessageSwitch: UISwitch!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!

@Published var canSendMessages: Bool = false
@Published var newMsg: String = ""

private var switchSubscriber: AnyCancellable?
private var btnSubscriber: AnyCancellable?


override func viewDidLoad() {
allowMessageSwitch.isOn = false
super.viewDidLoad()
setupProcesscingChain()
}

func setupProcesscingChain() {
switchSubscriber = $canSendMessages.receive(on: DispatchQueue.main).assign(to: \.isEnabled, on: sendButton)

btnSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text, on: messageLabel)
}

@IBAction func didSwitch (_ sender: UISwitch) {
canSendMessages = sender.isOn
}

@IBAction func sendMessage( _ sender: Any) {
}


}

我遇到错误
btnSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text, on: messageLabel)

错误消息是

Type of expression is ambiguous without more context



我不明白为什么标签不能作为切换器( bool )

我猜是因为 \.isEnabled不是可选的,并且 \.text是可选的..??

我怎样才能以相同的格式进行这项工作。这是用于练习和了解Combine 的工作原理.. 请帮助!

最佳答案

lableSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text!, on: messageLabel)

我自己解决了!这很简单。
只需强制解开 keyPath。

关于Swift结合问题与UILabel订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60406189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com