在iOS开发中有时我们会用到这种单选按钮组,只能而且必选一个按钮,
其实也非常简单
**1、定于两个属性按钮**
@property (nonatomic, strong) UIButton * sinaButton;
@property (nonatomic, strong) UIButton * bankButton;
2、初始化并默认一个选项,这里用了4个button,实际可以采用2个,因为写一半才发现后面的汉字也要设置成可点的,就懒得改了,直接改成button了
self.sinaButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
_sinaButton.frame = CGRectMake(30, 200, 15, 15);
[_sinaButton setBackgroundImage:[UIImage imageNamed:@"invest_delecte"] forState:(UIControlStateNormal)];
[_sinaButton setBackgroundImage:[UIImage imageNamed:@"invest_selecte"] forState:(UIControlStateSelected)];
[_sinaButton addTarget:self action:@selector(sinaAction:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:_sinaButton];
UIButton *sinaNme = [UIButton buttonWithType:(UIButtonTypeCustom)];
sinaNme.frame = CGRectMake(_sinaButton.right + 5, _sinaButton.top - 5, 100, 30);
[sinaNme setTitle:@"支付宝" forState:(UIControlStateNormal)];
[sinaNme setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
[sinaNme addTarget:self action:@selector(sinaAction:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:sinaNme];
self.bankButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
_bankButton.frame = CGRectMake(_sinaButton.left, _sinaButton.bottom + 20, _sinaButton.width, _sinaButton.height);
[_bankButton setBackgroundImage:[UIImage imageNamed:@"invest_delecte"] forState:(UIControlStateNormal)];
[_bankButton setBackgroundImage:[UIImage imageNamed:@"invest_selecte"] forState:(UIControlStateSelected)];
[_bankButton addTarget:self action:@selector(bankAction:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:_bankButton];
UIButton *banknameSelete = [UIButton buttonWithType:(UIButtonTypeCustom)];
banknameSelete.frame = CGRectMake(sinaNme.left , _bankButton.top - 5, 80, 30);
[banknameSelete setTitle:@"银行卡" forState:(UIControlStateNormal)];
[banknameSelete setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
[banknameSelete addTarget:self action:@selector(bankAction:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:banknameSelete];
// 先默认一个选项
_sinaButton.selected = YES;
3、通过点击事件做逻辑处理,不要混乱
- (void)sinaAction:(UIButton *)button
{
if (_sinaButton.selected) {
}
else if (!_sinaButton.selected)
{
_sinaButton.selected = YES;
_bankButton.selected = NO;
}
NSLog(@"支付宝");
}
- (void)bankAction:(UIButton *)button
{
if (_bankButton.selected) {
}
else if (!_bankButton.selected)
{
_bankButton.selected = YES;
_sinaButton.selected = NO;
}
NSLog(@"银行卡");
}
这样就完成了简单的单选按钮组