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

这篇写的是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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,229评论 4 61
  • NSValue NSValue对象是用来存储一个C或者Objective-C数据的简单容器。目的是为了允任意类型的...
    忠橙_g阅读 493评论 0 0
  • 今天第一次下载简读,首先喜欢的是它app的样式。怀着好奇心安装后点开来确实跟其他阅读类软件有所不同,权且用着。
    爱清新煊阅读 200评论 0 0
  • 一 刚看完《情书》。我嘤嘤哎哎地趴在桌上,整颗心就像一粒红豆,被这部九五年的片子煮开软烫的花。 室友凑过来看我哭了...
    感恩的plus阅读 561评论 0 1