let newLabel = UILbael()
let button = UIButton()
button.setValue(newLabel, forKeyPath: "titleLabel")
crash info
setValue:forUndefinedKey:]: this class is not key valuecoding-compliant for the key titleLabel
how do it if use kvc ?
let newLabel = UILbael()
let button = UIButton()
button.setValue(newLabel, forKeyPath: "titleLabel")
crash info
setValue:forUndefinedKey:]: this class is not key valuecoding-compliant for the key titleLabel
how do it if use kvc ?
You should use setTitle
method to set button title for states.
button.setTitle("Your button title here", for: .normal)
setValue(_:forKeyPath:) is a method from NSObject
class which UIButton
is a subclass of. It is not recommended to use KVO. Read this thread for more information.
KVC is only supported for NSObjects, and Apple seems to be phasing it out in Swift. I don't recommend using KVC for new development.
You also shouldn't use the button's titleLabel
to set the button's title. To quote the Apple docs on UIButton:
To set the actual text of the label, use
setTitle(_:for:)
(button.titleLabel.text does not let you set the text).
If you have two buttons, firstButton
and secondButton
, and you're trying to copy the title from the first to the second, your code might look like this:
let title = firstButton.title(forState: .normal)
secondButton.setTitle(title, for: .normal)
I think u have not confirmed your outlet in your ViewController that's a reason when use button and set title there are not any references of a button in ViewController. it's like the use of any object without any initialize. So make sure and check button outlet. Please see code so we make sure what is actual problem.