我有一个UIButton
当被触摸时应该执行一个动作然后改变颜色。当前调用了该操作,但需要点击两次才能更改按钮的颜色。我不知道为什么。
在viewDidLoad
方法中我设置了一个布尔值 toggleLikeIsOn = NO;
这也是在 viewDidLoad 中以编程方式的 UIButton
// 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);
这是按下按钮时调用的方法:
-(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;
}