在所选和默认之间更改UIButton图像

时间:2014-05-04 17:42:05

标签: objective-c xcode

我有以下用于在UIWebView中加载本地html文件。

- (IBAction)loadLocalFile:(id)sender

{
UIButton *tmp = sender;
int tag = (int)tmp.tag;
NSString *fileName = [NSString stringWithFormat:@"elec%i", tag];
NSURL *url = [NSURL URLWithString:@""];
NSString *filePath = @"";

switch (tag) {
    case 1:
    {
        filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"html"];
        break;
    }
    case 2:
    {
        filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"html"];
        break;
    }
    default:
        break;
}

url = [NSURL fileURLWithPath:filePath];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

我试图找到一种方法,当用户按下其中一个按钮时按钮图像改变(基本红色方块以强调位置),当用户按下视图中的另一个按钮时,第一个按钮返回到原始按钮状态,而选定的一个更改为新图像... 任何输入都非常感谢。 感谢!!!

我试过

button.selected = !button.selected;

它将图像更改为我想要的盒装图像,但是当按下另一个按钮时,前一个按钮不会返回到原始状态。

双按相同的按钮确实会将其恢复到原始状态。

1 个答案:

答案 0 :(得分:0)

环顾四周后,我发现了这个解决方案:

// Unselect all the buttons in the parent view
for (UIView *button in tmp.superview.subviews) {
if ([button isKindOfClass:[UIButton class]]) {
    [(UIButton *)button setSelected:NO];
}
}

// Set the current button as the only selected one
[tmp setSelected:YES];