objective-c - 如何制作多个单选按钮,但始终只选择一个,而第一个是默认的?
问题描述
我从事一个 Objective-C 项目并尝试构建多个单选按钮。不久,我想制作多个单选按钮,但始终只选择一个,其中第一个是默认的。
我开始尝试使用 2 个按钮,但我无法完全实现我想要的。我希望有很好的方法来做到这一点。我也可以扩展。
解决方案
您可以通过将 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);
}
}
推荐阅读
- reactjs - 反应选择加载异步选项不加载
- android - 通过 AWS-SNS 的 FCM-Push 通知延迟或必须打开屏幕才能接收通知
- typescript - 在打字稿中编写适当的克隆方法
- android - 如何在应用程序中读取通话和电子邮件历史记录 - Android 和 iOS
- kotlin - Kotlin 内置函数接受 Int 但我想传递 Long
- google-visualization - 谷歌图表条在 wkhtmltopdf 中正确高度的一半
- windows - 我如何等待工作进程完成但又限制它的时间?
- bash - Bash:在另一个窗口/应用程序中列出按下的键
- internet-explorer - Edge IE 模式和企业站点列表更新
- python - Pushshift Reddit 网页抓取循环中的代码效率/性能改进