简体   繁体   中英

Highlighted UIButton when is pressed won't highlight the first time is pressed

I have look around to highlight a button when is pressed and I came up with this..

//The button #1
-(IBAction)Number1:(UIButton *)sender{
    [self buttonPressed:sender];
    [self appendDigit:@"1"];
}

//The function for buttonPressed
- (void) buttonPressed:(UIButton *)sender {

    [sender setBackgroundImage:[UIImage imageNamed:@"ButtonPressed.png"] forState:(UIControlStateHighlighted)];
}

It highlights the button exactly how I want but only after the second time is pressed. Not sure why is doing this, but it is.. So, I'm wondering what am I missing here?

I have seen other posts which approach this in a different way but I fond that it was a bit different on how I implemented my calculator..

Well, I hope you guys can give a hand or guide in the right direction.. Thanks in advance..

The reason is this line of code

[sender setBackgroundImage:[UIImage imageNamed:@"ButtonPressed.png"] forState:(UIControlStateHighlighted)];

is NOT yet processed during the first tap.

You will have to make an IBOutlet of that button like

@property (weak, nonatomic) IBOutlet UIButton *button;

Then in viewDidLoad

    [self.button setBackgroundImage:[UIImage imageNamed:@"ButtonPressed.png"] forState:(UIControlStateHighlighted)];

Sample Project in Github: https://github.com/voyage11/HighLightBtn

You're setting the background image only after the button has been clicked once. Instead, move your "pressed" code into viewDidLoad or viewWillAppear. In other words, this code:

    [button setBackgroundImage:[UIImage imageNamed:@"ButtonPressed.png"] forState:(UIControlStateHighlighted)];

Here button should refer to your button, as in an IBOutlet.

Here's why: this line code doesn't mean "set the background to ButtonPressed.png this very moment." Instead, it means: "when this button's state changes to highlighted, the background should be ButtonPressed.png." As such, you need to run this line just once (not every time the button is pressed), and before the button gets pressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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