您的位置:首页 > 产品设计 > UI/UE

iOS的UIButton单选的最佳方式

2016-05-10 17:30 369 查看
#import "TestViewController.h"
#import "UIImage+Mycategory.h"

@interface TestViewController ()

@property (nonatomic,strong) UIButton *myButton;

@end

@implementation TestViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];

NSArray *btnArray = @[@"颜色",@"尺寸",@"空间",@"备注"];
for (int i = 0 ; i < btnArray.count; i ++) {
float width = (self.view.frame.size.width - 20 - 15)/4;
self.myButton = [[UIButton alloc]initWithFrame:CGRectMake(10 +  (width + 5) * i, 100, width , 30)];
[_myButton setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateNormal];
[_myButton setBackgroundImage:[UIImage imageWithColor:[UIColor orangeColor]] forState:UIControlStateSelected];
[_myButton setTitle:btnArray[i] forState:UIControlStateNormal];
_myButton.tag = 100 + i;
[_myButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];

if (i == 0) _myButton.selected = YES;else _myButton.selected = NO;

[self.view addSubview:_myButton];
}
}

- (void)clickAction:(UIButton *)button
{
if (button.tag != 100) {
UIButton *tempBtn = [self.view viewWithTag:100];
if (tempBtn.selected == YES) tempBtn.selected = NO;
}

if (button != self.myButton) {
self.myButton.selected = NO;
self.myButton = button;
}
self.myButton.selected = YES;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: