iOS for循环创建UIButton及点击处理


{

   //声明一个全局变量判断选中的按钮

    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];

}


 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值