Search code examples
objective-cuibuttonkey-valuekey-value-codingkvc

How do I change a UIButton's title using KVC?


I have an array of UIButtons and want to set all their titles to a specific value at once, without looping through the array. The only solution I've found is by means of Key-Value Coding, i.e. something like this:

[self.board setValue:@"X" forKeyPath:@"titleLabel.text"];

However, the button's titleLabel property is readonly and cannot be changed. I also tried using the button's title property as the keypath, but it doesn't work either.

I've done this before by changing the "enabled" property of all the buttons at once using KVC and it worked great, but if I want to change the titles it just won't work (I'm assuming this is because of the new ControlState feature of the UIButton which allows multiple titles for its various states).

So, does anyone have a one-liner solution (with no loops) to change the title of every button from the array?


Solution

  • Actually, KVC is working and is setting your text value. From the Apple Documentation: Although this property is read-only, its own properties are read/write. Use these properties to configure the appearance of the button label So textLabel is a UILabel and the text property on UILabel is not read only. The reason it does not appear to be working is that you are only changing the text of UILabel and not the frame size of the label which has a default value of (0, 0, 0, 0). If you initialise your buttons with a default value of "(three blanks)" for instance (rather than nil) then it will work. (However, there does still seem to be an issue where iOS resets the button value to it's initial value after you click on it)