简体   繁体   中英

UIButton image doesn't change when tapped

I need to have an image button change to a different image when I tap it. Simple enough, and there are samples out there, but they don't work for me. This is what I tried following the examples:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 270, 200, 40.0);
[button setImage:[UIImage imageNamed:@"butterfly3.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Submit" forState:UIControlStateNormal];
[scrollView button];

Now, I notice that my button is set to perform its action on UIControlEventTouchDown so I added it to the "clicked" control states like this:

[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected | UIControlStateHighlighted | UIControlEventTouchDown];

but the image still stays the same. What am I missing?

The issue was that my buttonPressed method did a long(ish) query on the main thread and for some reason the highlighting of the button doesn't work in such a case.

When I moved the query to a separate thread the highlight went back on.

For the sake of completion I'll bring the code here. Initially I was fetching objects through Parse.com API like this:

[myQuery findObjects]

This above does the query on the main thread and blocks everything else.

Then I changed it to fetching in a separate thread like this:

[myQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if(!error) {
            // whatever is needed to be done
        }
    } else {
        NSLog(@"Error while fetching objects %@", error.description);
    }
}];

Just change your code by this, and everything will work!

[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected];

Inside buttonPressed method set yourButton.selected = YES; Also set image as Miroslav mentioned.

It appears that you are putting an event mask UIControlEventTouchDown that is being interpreted as a state mask in this line:

[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected | UIControlStateHighlighted | UIControlEventTouchDown];

In fact I think you may not need this line at all, as you've already set the appropriate images. Try removing UIControlEventTouchDown from this line or comment out the whole line.

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