简体   繁体   English

setImage:forState不适用于UIButton的子类

[英]setImage:forState does not work for subclass of UIButton

I create a class RadioButton that inherited from UIButton ,and rewrite the method layoutSubViews where reset the frame of self.imageView and self.titleLabel ,when I call the method setImage:forState: of RadioButton instance,it does not work, but the method radioButton.imageView.image = [UIImage imageNamed:@""] work. 我创建了一个从UIButton继承的RadioButton类,并重写了layoutSubViews方法,在其中重置self.imageView和self.titleLabel的框架,当我调用RadioButton实例的setImage:forState:方法时,它不起作用,但是radioButton方法.imageView.image = [UIImage imageNamed:@“”]工作。 It is an interesting problem ,I appreciate so much if anyone know why and share the reason . 这是一个有趣的问题,如果有人知道原因并分享原因,我将非常感激。

When we set title,image for button we need to use below code 当我们设置标题,按钮的图像时,我们需要使用以下代码

For Button 对于按钮

[button setTitle:@"Your Title" forState:UIControlStateNormal];

For Image 对于图像

[button setImage:[UIImage imageNamed:@"Your Image Name"] forState:UIControlStateNormal];

why should not we use titleLabel 我们为什么不应该使用titleLabel

Do not use the label object to set the text color or the shadow color. 不要使用标签对象设置文本颜色或阴影颜色。 Instead, use the setTitleColor:forState: and setTitleShadowColor:forState: methods of this class to make those changes. 而是使用此类的setTitleColor:forState:和setTitleShadowColor:forState:方法进行更改。

The titleLabel property returns a value even if the button has not been displayed yet. 即使 尚未显示 按钮,titleLabel属性也会返回一个值 The value of the property is nil for system buttons. 对于系统按钮,该属性的值为nil。

why should we use setTitle 为什么要使用setTitle

Use this method to set the title for the button. 使用此方法设置按钮的标题。 The title you specify derives its formatting from the button's associated label object. 您指定的标题是从按钮的关联标签对象派生的。 If you set both a title and an attributed title for the button, the button prefers the use of the attributed title over this one. 如果同时为按钮设置了标题和属性标题,则该按钮将优先使用属性标题。

At a minimum, you should set the value for the normal state. 至少应设置正常状态的值。 If a title is not specified for a state, the default behavior is to use the title associated with the UIControlStateNormal state. 如果未为状态指定标题,则默认行为是使用与UIControlStateNormal状态关联的标题。 If the value for UIControlStateNormal is not set, then the property defaults to a system value. 如果未设置UIControlStateNormal的值,则该属性默认为系统值。

For Image 对于图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM