2

我有一个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;

}

4

1 回答 1

3

编辑:错过了你的最后一行。

第一:线

toggleLikeIsOn = NO;

是多余的。如果你在那部分代码中,toggleLikeIsOn 已经是 NO。

因此,当您第一次点击该按钮时,将执行 if 的 else 部分(如果您尚未将其设置为 YES,则 toggleLikeIsOn 为 NO)。在第一次调用期间,toggleLikeIsOn 变为 YES,然后在下一次调用此方法时,将执行 if 部分,更改颜色。

于 2013-09-09T10:17:46.117 回答