如何使用KVC更改UIButton的标题? [英] How do I change a UIButton's title using KVC?

查看:123
本文介绍了如何使用KVC更改UIButton的标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIButtons数组,想一次将所有标题设置为特定值,不循环.我发现的唯一解决方案是通过键值编码,即类似这样的东西:

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"];

但是,按钮的 titleLabel 属性为只读属性,无法更改.我也尝试使用按钮的 title 属性作为键路径,但是它也不起作用.

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.

我之前通过使用KVC一次更改所有按钮的"enabled"属性来做到这一点,并且效果很好,但是如果我想更改标题,那将是行不通的(我假设这是因为UIButton新增了ControlState功能,该功能允许在其各种状态下使用多个标题.

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?

推荐答案

实际上,KVC正在运行,并且正在设置文本值.从Apple文档中:尽管此属性是只读的,但其自身的属性是读/写的.使用这些属性来配置按钮标签的外观,因此textLabel是 UILabel ,并且不会读取 UILabel 上的 text 属性只要.它似乎不起作用的原因是,您仅更改了UILabel的文本,而不更改了默认值为(0,0,0,0)的标签的框架大小.例如,如果使用默认值(三个空格)"(而不是 nil )来初始化按钮,则它将起作用. (但是,在单击按钮后,iOS似乎仍然将按钮值重置为其初始值)

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)

这篇关于如何使用KVC更改UIButton的标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆