问题
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.titleLabel.font = [UIFont boldSystemFontOfSize:14];
[button setBackgroundImage:stretchableButtonImageNormal
forState:UIControlStateNormal];
[button setBackgroundImage:stretchableButtonImagePressed
forState:UIControlStateHighlighted];
[button setBackgroundImage:stretchableButtonImagePressed
forState:UIControlStateSelected];
回答1:
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 ;)
回答2:
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...
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.)
回答3:
[_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.
来源:https://stackoverflow.com/questions/7136510/how-to-set-the-button-image-for-uicontrolstateselected