我的故事板上有7个按钮,我为每个按钮都关联了一个标签号。而且所有按钮都连接到单个IBAction。
在我的操作方法中,我有一个类似window.alert()
的switch语句
根据标签运行适当的操作。一切正常。
但是我想添加一个功能,使选中的按钮突出显示,其余按钮处于正常状态。
答案 0 :(得分:0)
希望这可以给您一些想法:
- (void)setupButtons {
for (int i = 0; i < 7; i++) {
CGFloat width = self.view.frame.size.width / 7;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 100, width, 30)];
[self.view addSubview:button];
button.tag = 1000 + i;
[button setTitle:[NSString stringWithFormat:@"%d", i] forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
if (i == 0) {
// default first button selected
button.selected = YES;
}
}
}
- (void)buttonClicked:(UIButton *)sender {
for (int i = 0; i < 7; i++) {
UIButton *button = [self.view viewWithTag:(1000+i)];
button.selected = (button.tag == sender.tag);
}
}
答案 1 :(得分:0)
您可以使用标签创建属性:
@property (nonatomic, strong) NSArray *tags;
某处(例如,在viewDidLoad中)使用情节提要中使用的值对其进行初始化:
tags = @[@1, @2, @3, @4, @5]
然后使用此标签选择按钮
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < tags.count; i++) {
UIButton *button = [self.view viewWithTag:tags[i]];
button.selected = (button.tag == sender.tag);
}
}
或者您可以为每7个按钮创建IBOutlet并为其创建数组。
array = @[outlet1, ..., outlet7]
然后使用插座选择按钮
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < array.count; i++) {
UIButton *button = array[i];
button.selected = (button.tag == sender.tag);
}
}