开发者

How to set the button image for UIControlStateSelected

开发者 https://www.devze.com 2023-03-30 02:38 出处:网络
Hi I want to change the background of my button after I press the button i.e. the button should not change back to the previous image.

Hi I want to change the background of my button after I press the button i.e. the button should not change back to the previous image.

However, I am not able to do so. My code as follows. Can anyone advise how I can change the image to "custom_button_highlight" after I click on the button?

UIImage *buttonImageNormal = [UIImage imageNamed:@"custom_button"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal
                                         stretchableImageWithLeftCapWidth:12 topCapHeight:0];

UIImage *buttonImagePressed = [UIImage imageNamed:@"custom_button_highlight"];
UIImage *stretchableButtonImagePressed = [buttonImagePressed
                                          stretchableImageWithLeftCapWidth:12 topCapHeight:0];

button.t开发者_如何学CitleLabel.font = [UIFont boldSystemFontOfSize:14];
[button setBackgroundImage:stretchableButtonImageNormal
                  forState:UIControlStateNormal];

[button setBackgroundImage:stretchableButtonImagePressed
                  forState:UIControlStateHighlighted];

[button setBackgroundImage:stretchableButtonImagePressed
                  forState:UIControlStateSelected];


METHOD1

I see that you are using code to generate UIButton. It's easier to use Interface builder. Try this - In Interface builder (Xcode4), create the button & open the right sidebar. After that select the button, & the type of button as custom. After that in state config, there are various states, for each state you can set an image in image. Hope this helps...

How to set the button image for UIControlStateSelected

METHOD2

If you want to use code to generate UIButton (it beats me why) then you seem to be doing the right thing. Are you sure the images are there in your bundle? You did not include the image extension (like .jpg etc.)


You mentioned, that you don't want the image to change back... then instead of setting it for the states highlighted or selected, you have to set it for the state UIControlStateNormal.

But since you need it after it's been pressed, you have to catch the event that your button has been pressed and set the background image in there.

Hope it helped ;)


[_buttonConfirm setImage:[UIImage imageNamed:@"s.png"] forState:UIControlStateSelected ];

... does what you want programatically, not the background image. But I think you should follow Srikar's answer and use interface builder if you can.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号