我如何一次只允许一个选定的按钮? / make按钮知道我是否点击其他地方

时间:2011-06-03 06:51:44

标签: iphone objective-c select uibutton

如何制作这些按钮,以便一次只能使用一个按钮?我运行顺便说一句,我现在没有得到任何错误。我只是在寻找解决方案来解决我的挑战。谢谢你的帮助

它们是在for循环中生成的,如下所示:

    for (int l=0; l<list.length; l++) {  

        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton setTag:l];
        CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
        aButton.frame = buttonRect;

        [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [aButton setTitle:@" " forState:UIControlStateNormal];
        [gameScroll addSubview:aButton];
}

然后单击按钮时的操作是:

- (void) buttonClicked:(UIButton *)sender {

    int tag = sender.tag;

    if (sender.selected == TRUE) {
        [sender setSelected:FALSE];
        [sender setBackgroundColor:[UIColor clearColor]];
    }
    else if (sender.selected == FALSE) {
        [sender setSelected:TRUE];
        [sender setBackgroundColor:[UIColor redColor]];
    }
}

现在一切正常但我希望它知道是否已经选择了一个按钮并取消选择其他按钮,否则会在用户点击该按钮范围之外的任何时候自动取消选择 < / p>

提前致谢

2 个答案:

答案 0 :(得分:5)

我建议在按钮初始化中将所有按钮放到数组

NSMutableArray* buttons = [NSMutableArray arrayWithCapacity: list.length];

for (int l=0; l<list.length; l++) {  

        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton setTag:l];
        CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
        aButton.frame = buttonRect;

        [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [aButton setTitle:@" " forState:UIControlStateNormal];
        [gameScroll addSubview:aButton];
        [buttons addObject: aButton];
}

每次触发按钮点击,然后执行你的逻辑:

for (UIButton* button in buttons)
    {
        if (button != sender)
        {
             [button setSelected: FALSE];
             [button setBackgroundColor:[UIColor redColor]];
        }
    }

int tag = sender.tag;

    if (sender.selected == TRUE) {
        [sender setSelected:FALSE];
        [sender setBackgroundColor:[UIColor clearColor]];
    }
    else if (sender.selected == FALSE) {
        [sender setSelected:TRUE];
        [sender setBackgroundColor:[UIColor redColor]];
    }

希望有帮助:)

答案 1 :(得分:1)

您可以将当前选定的按钮存储在单独的变量中,然后在buttonClicked中取消选择:方法:

- (void) buttonClicked:(UIButton *)sender {

    int tag = sender.tag;

    currentButton.selected = NO;
    if (currentButton != sender){
       currentButton = sender;
       currentButton.selected = YES;
    }
    else{
       currentButton = nil;
    }
}

您还可以在按钮本身中为每个状态指定背景颜色,这样您实际上不需要每次手动更改它

如果您还想在用户触摸屏幕时取消选择按钮,您可以在视图控制器中实现touchesEnded:withEvent:并在其中重置currentButton(如果没有其他控件拦截触摸事件,该方法将被调用 - 所以它在所有情况下可能都不够)

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{
    currentButton.selected = NO;
    currentButton = nil;
}