UIButton
触れたときにアクションを実行してから色を変える必要があります。現在、アクションは呼び出されていますが、ボタンの色を変更するには 2 回タップする必要があります。理由がわかりません。
メソッドで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;
}