-4
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 ?

loseDream
  • 87
  • 1
  • 13
  • 1
    can you show your code ? – Mahesh Dangar Aug 18 '18 at 09:33
  • 1
    What are you trying to achieve? – Ashley Mills Aug 18 '18 at 09:38
  • 1
    Your question is ambiguous. You post some code that doesn't really make sense and then say "how to do it." How do do **what**? Describe what you're trying do in words. Are you trying to copy the text from a label "titleLablel" into another label, "newLabel"? Are you trying to copy all the attributes of the label? (Size, position, font, etc.) – Duncan C Aug 18 '18 at 12:01
  • var button = button() set button.titlelabel use kvc – loseDream Aug 18 '18 at 12:37
  • **don't** use KVC – Duncan C Aug 18 '18 at 12:42
  • 1
    Your question is still a gabled mess. What are the variables containing the 2 buttons? How is the first button created? Is `newLabel` a label, or are you hoping to copy the button title of one button to another? – Duncan C Aug 18 '18 at 12:43

3 Answers3

2

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.

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
1

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)
Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

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.

nimesh surani
  • 177
  • 1
  • 13