UIButton设置titleLabel setValue(newLabel,forKeyPath:“ titleLabel”)

时间:2018-08-18 09:27:28

标签: ios swift uibutton

let newLabel = UILbael()
let button = UIButton()
button.setValue(newLabel, forKeyPath: "titleLabel")

崩溃信息

  

setValue:forUndefinedKey:]: this class is not key valuecoding-compliant for the key titleLabel

如果使用kvc怎么办?

3 个答案:

答案 0 :(得分:2)

您应该使用setTitle方法来设置状态的按钮标题。

button.setTitle("Your button title here", for: .normal)

setValue(_:forKeyPath:)是来自NSObject类的方法,其中UIButton是其子类。不建议使用KVO。阅读此thread了解更多信息。

答案 1 :(得分:1)

KVC仅受NSObjects支持,Apple似乎正在Swift中逐步淘汰它。我不建议将KVC用于新开发。

您也不应该使用按钮的titleLabel来设置按钮的标题。引用UIButton上的Apple文档:

  

要设置标签的实际文本,请使用setTitle(_:for:)   (button.titleLabel.text不允许您设置文本)。

如果您有两个按钮,firstButtonsecondButton,并且您试图将标题从第一个复制到第二个,则代码可能如下所示:

let title = firstButton.title(forState: .normal)
secondButton.setTitle(title, for: .normal)

答案 2 :(得分:0)

我认为您尚未确认您在ViewController中的插座,这是使用按钮和设置标题时在ViewController中没有按钮引用的原因。就像使用没有初始化的任何对象。因此,请确保并检查按钮插座。请查看代码,以便我们确定真正的问题。

相关问题