美文网首页
iOS 循环创建自适应宽度button

iOS 循环创建自适应宽度button

作者: wang521921 | 来源:发表于2018-11-19 14:51 被阅读0次
    屏幕快照 2018-11-19 下午2.53.37.png

    NSArray *arr = @[@"无知",@"风云变幻",@"施耐庵",@"唉",@"西门吹雪",@"呵呵哒",@"快看看",@"窿窿啦啦",@"一杆禽兽狙",@"合欢花",@"暴走大事件",@"非诚勿扰",@"呵呵呵"];

    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    
    CGFloat h = 200;//用来控制button距离父视图的高
    
    for(int i = 0; i < arr.count; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        button.tag = 100+ i;
        
        button.backgroundColor = [UIColor whiteColor];
        
        button.layer.masksToBounds = YES;
        
        button.layer.cornerRadius = 25/2;
        
        [button.layer setBorderColor:[UIColor colorWithRed:51/255.0 green:141/255.0 blue:188/255.0 alpha:1].CGColor];
        
        [button.layer setBorderWidth:1];
        
        [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [button setTitleColor:[UIColor colorWithRed:51/255.0 green:141/255.0 blue:188/255.0 alpha:1] forState:UIControlStateNormal];
        
        //根据计算文字的大小
        
        
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        
        CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        
        //为button赋值
        
        [button setTitle:arr[i] forState:UIControlStateNormal];
        
        //设置button的frame
        
        button.frame = CGRectMake(10+ w, h, length + 35, 30);
        
        //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
        
        if(10+ w + length + 35> self.view.frame.size.width){
            
            w = 0; //换行时将w置为0
            
            h = h + button.frame.size.height + 10;//距离父视图也变化
            
            button.frame = CGRectMake(10+ w, h, length + 35, 30);//重设button的frame
            
        }
        
        w = button.frame.size.width + button.frame.origin.x;
        
        [self.view addSubview:button];
        
    }
    
    • (void)handleClick:(UIButton *)btn{

      NSLog(@"%ld",btn.tag);

    }

    相关文章

      网友评论

          本文标题:iOS 循环创建自适应宽度button

          本文链接:https://www.haomeiwen.com/subject/wixafqtx.html