美文网首页
循环创建按钮并且间距一至

循环创建按钮并且间距一至

作者: 叫我小哥哥 | 来源:发表于2017-08-29 11:36 被阅读17次

这篇写的是for循环创建按钮,对于那些不太会计算坐标的同学会有帮助。不说太多直接上代码。

NSArray *title = [[NSArray alloc]initWithObjects:@"社",@"会",@"文",@"明",@"你",@"我",@"他",nil];
float Start_X = 10.0f;      // 第一个按钮的X坐标
float Start_Y = 50.0f;      // 第一个按钮的Y坐标
float Width_Space = 10.0f;   // 2个按钮之间的横间距
float Height_Space = 10.0f;  // 竖间距
// 每个按钮的宽度 记住 一定要把一行中多有按钮的边距都要算上并减掉 不然按钮会跑到屏幕外面去 这个5就是5个间距(左右各一个加中间3个间距) 4就是一行4个
float width = (WIDTH - 5 * Width_Space)/4; 
float height = 100.0; // 按钮高度
for (int i = 0; i < title.count; i++) {
     UIButton *button = [[UIButton alloc]init];
     button.tag = 100 + i;
     NSInteger index = i % 4; // 一行4个
     NSInteger page = i / 4;  // 列数
     button.frame = CGRectMake(index * (width + Width_Space) + Start_X, page  * (height + Height_Space)+Start_Y,width , height);
// 这个也可以 不过这个就是把上面的给拆分了而已 
 //    button.frame = CGRectMake(index * width + (index + 1) * Width_Space, page * height + (page + 1) * Height_Space + 30, width, height);
 // 设置字体大小   
button.titleLabel.font = [UIFont boldSystemFontOfSize:14];
// 设置按钮字体颜色  这里给的随即色   
[button setTintColor: [UIColor   colorWithRed:arc4random()%256/255.0f green:arc4random()%256/255.0f blue:arc4random()%256/255.0f alpha:1]];
// 添加背景色 这里给的随即色
button.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0f green:arc4random()%256/255.0f blue:arc4random()%256/255.0f alpha:1];


//按钮事件
[button addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void)btn:(UIButton *)sender{
    NSLog(@"tag = %ld",sender.tag);
}

最后上个效果图

DF1A22CB-835D-43C8-AD83-743BA0CCD400.png

如有问题请留言,看到后会回复。谢谢

相关文章

网友评论

      本文标题:循环创建按钮并且间距一至

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