gpt4 book ai didi

ios - UIButton 在 HighLighted 时不会改变图片,只会将图片设置为灰色

转载 作者:行者123 更新时间:2023-11-29 03:56:34 37 4
gpt4 key购买 nike

我希望图片在用户触摸它的那一刻就变成黄色。现在,第一次点击时图像会变成灰色,释放时图像会变成黄色。第二次点击图片会立即变回红色。我该如何解决这个问题?

-(void)bMethod:(UIButton*)sender
{
sender.selected = !sender.selected;
}

- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
UIImage *buttonImageSelected = [UIImage imageNamed:@"yellow.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchDown];
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImageSelected forState:UIControlStateSelected];
[myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
[self.view addSubview:myButton];

最佳答案

我运行了你的代码,它工作得很好,伙计。只需仔细检查图像名称即可!

编辑1:

将您的代码替换为以下内容:

    -(void)bMethod:(UIButton*)sender
{
if (sender.imageView.image != [UIImage imageNamed:@"red.png"]){
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateNormal];
}
else{
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];
}
}

- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchDown];
[myButton setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];
}

编辑 2:

-(void)bMethod:(UIButton*)sender
{
sender.selected = !sender.selected;
sender.highlighted = !sender.highlighted;
}

- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
UIImage *buttonImageSelected = [UIImage imageNamed:@"yellow.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchUpInside];
myButton.adjustsImageWhenHighlighted = NO;
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImageSelected forState:UIControlStateSelected];
[myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
[self.view addSubview:myButton];
}

关于ios - UIButton 在 HighLighted 时不会改变图片,只会将图片设置为灰色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16415153/

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