gpt4 book ai didi

ios - 在同一选项卡上的三个 UIButton 之间切换 selectedState

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:06:51 25 4
gpt4 key购买 nike

我在同一个选项卡上有 3 个 UIButton。

问题:当我点击按钮 1 时,按钮 2 和按钮 3 都被选中;但是我想要的是当我选择(例如)button2 时,其他按钮未被选中(如 html 上的单选按钮)。关于如何解决这个问题的任何想法?

这是我的代码:

- (IBAction)button1:(UIButton *)sender {
sender.selected = !sender.selected;
}
- (IBAction)button2:(UIButton *)sender {
sender.selected = !sender.selected;
}
- (IBAction)button3:(UIButton *)sender {
sender.selected = !sender.selected;
}

最佳答案

有几个简单的解决方案。也许它们不是最优的,但您可以使用它们:

第一种解决方案:

将您的按钮与相应的属性链接起来:

@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;

在每个操作中更改每个按钮的selected 属性:

- (IBAction)button1Clicked:(UIButton *)sender {
_button1.selected = YES;
_button2.selected = NO;
_button3.selected = NO;
}

第二种方案:

在 NSArray 中添加所有按钮:

NSArray *buttonsArray = [[NSArray alloc] initWithObjects: button1, button2, button3, nil];

然后用一个 Action 链接所有的按钮:

- (IBAction)buttonClicked:(UIButton *)sender {
for (UIButton *btn in _buttonsArray) {
if (btn == sender)
btn.selected = YES;
else
btn.selected = NO;
}
}

不要忘记让类的所有方法都可以访问您的 NSArray,例如通过创建相应的属性:

@property (weak, nonatomic) NSArray *buttonsArray;

第三种方案:

您可以更改每个按钮的标记属性(通过 Interface Builder 或在代码中):

_button1.tag = 1;
_button2.tag = 2;
_button3.tag = 3;

然后用一个 Action 链接所有按钮(就像前面的例子一样):

- (IBAction)buttonClicked:(UIButton *)sender {
if (sender.tag == 1) {
_button1.selected = YES;
_button2.selected = NO;
_button3.selected = NO;
} else if (sender.tag == 2) {
_button1.selected = NO;
_button2.selected = YES;
_button3.selected = NO;
} else if (sender.tag == 3) {
_button1.selected = NO;
_button2.selected = NO;
_button3.selected = YES;
}
}

第四种解决方案:(@velmurugan-s)

对所有按钮使用一个 Action 并将它们的默认状态设置为selected = NO:

- (IBAction)buttonClicked:(UIButton *)sender {
_button1.selected = NO;
_button2.selected = NO;
_button3.selected = NO;

sender.selected = YES;
}

总结:

我建议您使用第二种解决方案作为最佳解决方案。

关于ios - 在同一选项卡上的三个 UIButton 之间切换 selectedState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452443/

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