gpt4 book ai didi

iphone - 如何让 UIButton 在触摸时改变颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:08:55 24 4
gpt4 key购买 nike

我有一个 UIButton,当它被触摸时应该执行一个 Action 然后改变颜色。当前已调用该操作,但需要轻按两次才能更改按钮的颜色。我不明白为什么。

viewDidLoad 方法中我设置了一个 bool 值 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;

最佳答案

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

首先:线

toggleLikeIsOn = NO;

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

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

关于iphone - 如何让 UIButton 在触摸时改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com