Reputation: 1681
I have a UIButton
that when touched should perform an action and then change color. Currently the action is called but it takes two taps to change the color of the button. I can't figure out why.
in the viewDidLoad
method I have set a boolean value toggleLikeIsOn = NO;
here's the UIButton programmatically also in viewDidLoad
// Like Btn
likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[likeButton addTarget:self
action:@selector(likeBtnPress)
forControlEvents:UIControlEventTouchUpInside];
likeStringForButton = [NSString stringWithFormat:@"LIKE [%@]",likesCount];
UIImage *likeInButtonImage = [UIImage imageNamed:@"like.png"];
[likeButton setTitle:likeStringForButton forState:UIControlStateNormal];
[likeButton setImage:likeInButtonImage forState:UIControlStateNormal];
likeButton.frame = CGRectMake(112.5, 330.0, 98.0, 28.0);
and here's the method that's called when the button is pressed:
-(void)likeBtnPress {
if(toggleLikeIsOn){
// use token with url for json data from contents of url
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"token"];
NSString *urlString = [NSString stringWithFormat:@"%@%@/likes?token=%@", kIDURL, listingId, savedValue];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
switch (categoryId) {
case 9:
likeButton.backgroundColor = customColor1;
break;
case 10:
likeButton.backgroundColor = customColor2;
break;
case 11:
likeButton.backgroundColor = customColor3;
break;
case 12:
likeButton.backgroundColor = customColor4;
break;
default:
break;
}
}
else {
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"token"];
NSString *urlString = [NSString stringWithFormat:@"%@%@/likes?token=%@", kIDURL, listingId, savedValue];
NSLog(@"urlstring is %@",urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"DELETE"];
[NSURLConnection connectionWithRequest:request delegate:self];
likeButton.backgroundColor = [UIColor blackColor];
toggleLikeIsOn = NO;
}
toggleLikeIsOn = !toggleLikeIsOn;
}
Upvotes: 2
Views: 418
Reputation: 3763
Edit: missed your last line.
First: the line
toggleLikeIsOn = NO;
Is redundant. If you are in that part of the code toggleLikeIsOn is already NO.
So the first time you tap that button, the else-part of the if is executed (toggleLikeIsOn is NO if you have not set it to YES yet). During that first call toggleLikeIsOn becomes YES, and then the next time this method is called, the if-part will get executed, changing the color.
Upvotes: 3