gpt4 book ai didi

objective-c - 如何在触摸按钮时更改 UIButton 图像

转载 作者:行者123 更新时间:2023-11-28 22:42:13 24 4
gpt4 key购买 nike

我试图在触摸按钮时更改 UIButton 图像。目前我它发生了变化,但仅在突出显示的状态发生变化时发生。我希望它改变并留在那里。我尝试了 UIControlStateSelected 来改变状态,但没有成功。

感谢帮助

这是我的代码:

 // Create buttons for the sliding category menu.
NSMutableArray* buttonArray = [NSMutableArray array];
NSArray * myImages = [NSArray arrayWithObjects:@"category-cafe-unsel.png", @"category-food-unsel.png", @"category-clothing-unsel.png", @"category-health-unsel.png", @"category-tech-unsel_phone.png" , @"category-tech2-unsel.png", @"catefory-theatre-unsel.png", @"category-travel-unsel.png", nil];

NSArray * myImagesSel = [NSArray arrayWithObjects:@"category-cafe-sel.png", @"category-food-sel.png", @"category-clothing-sel.png", @"category-health-sel.png", @"category-tech-sel_phone.png" , @"category-tech2-sel.png", @"catefory-theatre-sel.png", @"category-travel-sel.png", nil];

// only create the amount of buttons based on the image array count
for(int i = 0;i < [myImages count]; i++)
{
// Custom UIButton

btn = [UIButton buttonWithType:UIButtonTypeCustom];

[btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
[btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:i]] forState:UIControlStateHighlighted];

NSLog(@"The button title is %@ ", btn.titleLabel.text);

[btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonArray addObject:btn];

最佳答案

在您的 IBAction 方法中添加以下行:

 - (IBAction)change:(id)sender
{
UIButton *button = (UIButton *)sender;
int tagOfButton = button.tag - 1;
[button setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:tagOfButton]] forState:UIControlStateNormal];
}

将一行添加到您的 for 循环中,例如:

for(int i = 0;i < [myImages count]; i++)
{
// other stuffs
btn.tag = i+1;
}

编辑:

如果您需要在单击其他按钮时撤消之前的选择:

在您的 IBAction 方法中编写此循环。

for(int i = 0;i < [myImages count]; i++)
{
UIButton *but = (UIButton *)[buttonArray objectAtIndex:i];
if(but != button)
{
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
}
}

或者简单地将之前的按钮标签存储到一个变量中。并使用它来更改未完成的图像更改。

关于objective-c - 如何在触摸按钮时更改 UIButton 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14213520/

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