提问人:loseDream 提问时间:8/18/2018 最后编辑:loseDream 更新时间:10/11/2018 访问量:884
UIButton 设置 titleLabel setValue(newLabel, forKeyPath: “titleLabel”)
UIButton set titleLabel setValue(newLabel, forKeyPath: "titleLabel")
问:
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 怎么办?
答:
2赞
Rakesha Shastri
8/18/2018
#1
您应该使用 method 来设置状态的按钮标题。setTitle
button.setTitle("Your button title here", for: .normal)
setValue(_:forKeyPath:) 是 class 中的方法,它是 的子类。不建议使用KVO。有关详细信息,请阅读此线程。NSObject
UIButton
评论
0赞
Iraniya Naynesh
8/18/2018
仅供参考:UIButton 不是 NSObject 的子类,它继承自 UIControl
1赞
Rakesha Shastri
8/18/2018
@IraniyaNaynesh UIButton -> UIControl -> UIView -> UIResponder ->NSObject。
0赞
Iraniya Naynesh
8/18/2018
编码到这个每个类都是 NSObject 的子类 :-p
0赞
Rakesha Shastri
8/18/2018
@IraniyaNaynesh 是的,大多数 UIKit 对象都是。有没有一个词可以说子类的子类子类的子类的子类?我不知道有没有。:x
0赞
loseDream
8/18/2018
var button = button() set button.titlelabel 使用 kvc
0赞
nimesh surani
8/18/2018
#2
我认为您还没有在 ViewController 中确认您的插座,这是使用按钮和设置标题时 ViewController 中没有任何按钮引用的原因。这就像在没有任何初始化的情况下使用任何对象一样。因此,请确保并检查按钮插座。请参阅代码,以便我们确定实际问题是什么。
评论
0赞
loseDream
8/18/2018
var button = button() set button.titlelabel 使用 kvc
1赞
Duncan C
8/18/2018
#3
KVC 仅支持 NSObjects,而 Apple 似乎正在 Swift 中逐步淘汰它。我不建议将KVC用于新开发。
您也不应该使用按钮来设置按钮的标题。要在 UIButton 上引用 Apple 文档:titleLabel
若要设置标签的实际文本,请使用 (button.titleLabel.text 不允许您设置文本)。
setTitle(_:for:)
如果有两个按钮和 ,并且尝试将标题从第一个按钮复制到第二个按钮,则代码可能如下所示:firstButton
secondButton
let title = firstButton.title(forState: .normal)
secondButton.setTitle(title, for: .normal)
评论
newLabel