如何创建自定义UIButton(带图像)但仍然使用setTitle?

时间:2009-07-14 02:06:18

标签: iphone uibutton background-image

我尝试使用UIButtonTypeCustom创建一个UIButton。然后使用以下方法调整它的外观

[sendButton setImage:[UIImage imageNamed:@"sendButtonOff.png"] forState:UIControlStateNormal];
[sendButton setImage:[UIImage imageNamed:@"sendButtonOn.png"] forState:UIControlStateHighlighted];      
[sendButton setImage:[UIImage imageNamed:@"sendButtonDisabled.png"] forState:UIControlStateDisabled];

然而问题是,一旦你开始将UIImages设置为状态,setTitle就不再有效了。我认为setTitle只适用于非UIButtonTypeCustom?这意味着我要么必须将文本放入图像本身(不是很健壮),要么将其子类化并在视图中添加UILabel?听起来很多工作:(任何想法?

1 个答案:

答案 0 :(得分:10)

如果您希望标题显示在图像上,请尝试使用:

[sendButton setBackgroundImage:[UIImage imageNamed:@"sendButtonOff.png"] forState:UIControlStateNormal];
[sendButton setBackgroundImage:[UIImage imageNamed:@"sendButtonOn.png"] forState:UIControlStateHighlighted];      
[sendButton setBackgroundImage:[UIImage imageNamed:@"sendButtonDisabled.png"] forState:UIControlStateDisabled];