Search code examples
iosswiftuibuttonkey-value-coding

Why UIButton can not use KVC to change titleLabel


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 ?


Solution

  • Observe that you can't set the title label directly:

    mybutton.titleLabel = UILabel(...)
    

    The reason: it's a read-only property. You have no business trying to substitute a different label inside the button!