{
//声明一个全局变量判断选中的按钮
UIButton *selectedBtn;
}
- (void)addButton:(UIView *)view{
NSArray *arr = @[@"1",@"5",@"10",@"20",@"50"];
CGFloat w =0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
CGFloat h = 200;//用来控制button距离父视图的高
for (int i =0; i < arr.count; i++) {
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];
button.layer.cornerRadius=5;
button.layer.masksToBounds =YES;
button.tag = i+1;
//默认选中第一个
if (button.tag==1) {
button.backgroundColor = [UIColorredColor];
selectedBtn=button;
}else{
button.backgroundColor = [UIColorwhiteColor];
}
[button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
[buttonsetTitleColor:[UIColorcolorWithRed:0.000green:0.502blue:1.000alpha:1.000]forState:UIControlStateNormal];
//获取字号
NSDictionary *attributes = @{NSFontAttributeName:[UIFontsystemFontOfSize:18]};
//根据计算文字的大小
CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320,2000)options:NSStringDrawingUsesLineFragmentOriginattributes:attributescontext:nil].size.width;
//为button赋值
[buttonsetTitle:[NSStringstringWithFormat:@"%@元",arr[i]]forState:UIControlStateNormal];
//设置button的frame
length=45;//此行固定宽度取消调此行恢复自动计算Tittle长度
button.frame =CGRectMake(10 + w, h, length +15 , 50);
//当button的位置超出屏幕边缘时换行 320只是button所在父视图的宽度
if(10 + w + length +15 > view.frame.size.width){
w = 0;//换行时将w置为0
h = h + button.frame.size.height + 10;//距离父视图也变化
button.frame =CGRectMake(15 + w, h, length +15, 50);//重设button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[view addSubview:button];
}
}
//点击事件
- (void)handleClick:(UIButton *)btn{
NSLog(@"点击了%ld",btn.tag);
//选中变红色 其他按钮变为白色
if (selectedBtn) {
selectedBtn.backgroundColor = [UIColorwhiteColor];
}
selectedBtn = btn;
selectedBtn.backgroundColor = [UIColorredColor];
}