首页 > 解决方案 > 如何制作多个单选按钮,但始终只选择一个,而第一个是默认的?

问题描述

我从事一个 Objective-C 项目并尝试构建多个单选按钮。不久,我想制作多个单选按钮,但始终只选择一个,其中第一个是默认的。

我开始尝试使用 2 个按钮,但我无法完全实现我想要的。我希望有很好的方法来做到这一点。我也可以扩展。

标签: objective-cuibutton

解决方案


您可以通过将 UI 元素放入其中来对它们进行分组,UIView并使用 KVO 观察器来利用额外的代码。

@interface ViewController ()
@property (nonatomic) UIView *group;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createGroupWithRadios:3 andSelectIndex:0];
}

//a context to make KVO much easier to catch (and less string compare'y)
static void * kRadioGroupContext = &kRadioGroupContext;

-(void)createGroupWithRadios:(int)amount andSelectIndex:(int)idx {
    CGFloat h = 30.0;
    _group = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, h*amount)];
    for (int i=0; i<amount; i++) {
        UIButton *radio = [UIButton buttonWithType:(UIButtonTypeSystem)];
        radio.tag = i;
        radio.selected = i==idx;
        { //style stuff
            radio.frame = CGRectMake(0, h*i, 100, h);
            [radio setTitle:@"off" forState:UIControlStateNormal];
            [radio setTitle:@"on" forState:UIControlStateSelected];
            [radio setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [radio setTitleColor:UIColor.redColor forState:UIControlStateSelected];
            //[radio setImage:[UIImage imageNamed:@"active"] forState:UIControlStateSelected];
            //[radio setImage:[UIImage imageNamed:@"inactive"] forState:UIControlStateNormal];
        }
        [radio addTarget:self action:@selector(radioButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [_group addSubview:radio];
    }
    [self.view addSubview:_group];

    //you can use _group.tag to keep which one is selected and observe it
    _group.tag = idx;
    [_group addObserver:self forKeyPath:@"tag" options:(NSKeyValueObservingOptionNew) context:kRadioGroupContext];
}

-(void)radioButtonPressed:(UIButton*)sender {
    _group.tag = sender.tag;
    for (int i=0; i<_group.subviews.count; i++) {
        UIButton *radio = _group.subviews[i];
        radio.selected = radio.tag==sender.tag;
    } 
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (context == kRadioGroupContext) {
        // do something when a new radio is selected
        NSLog(@"selected Radio %lu", _group.tag);
    }
}

推荐阅读