How to create a custom UIButton (with images) but

2019-05-24 09:23发布

问题:

I've tried creating a UIButton with UIButtonTypeCustom. Then afterwards used the following methods to adjust the look of it

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

However the problem is, once you start setting UIImages to the states, setTitle no longer works. I think setTitle only works with non-UIButtonTypeCustom? This means I either have to put the text into the images themselves (not very robust) or subclass this and add a UILabel to the view? Sounds like alot of work :( Any ideas?

回答1:

If you want the title to display over the image, try using this:

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