iOS自适应button循环创建

NSArray *arr = @[ @" 无知 " , @" 风云变幻 " , @" 施耐庵 " , @" " , @" 西门吹雪 " , @" 呵呵哒 " , @" 快看看 " , @" 窿窿啦啦 " , @" 一杆禽兽狙 " , @" 合欢花 " , @" 暴走大事件 " , @" 非诚勿扰 " , @" 呵呵呵 " ] ;
  CGFloat w = 0 ; // 保存前一个 button 的宽以及前一个 button 距离屏幕边缘的距离
CGFloat h = 100 ; // 用来控制 button 距离父视图的高
for ( int i = 0 ; i < arr. count ; i++) {
UIButton *button = [ UIButton buttonWithType : UIButtonTypeSystem ];
button.
tag = 100 + i;
button.
backgroundColor = [ UIColor colorWithRed : 239 / 255.0 green : 239 / 255.0 blue : 244 / 255.0 alpha : 1 ];
[button
addTarget : self action : @selector (handleClick:) forControlEvents : UIControlEventTouchUpInside ];
[button
setTitleColor :[ UIColor colorWithWhite : 0.400 alpha : 1.000 ] 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 + 15 , 30 );
       
button.
layer . cornerRadius = 4 ;
       
button.
layer . masksToBounds = YES ;
       

//
button 的位置超出屏幕边缘时换行 320 只是 button 所在父视图的宽度
  if ( 10 + w + length + 15 > 355 ){
      w =
0 ; // 换行时将 w 置为 0
      h = h + button.
frame . size . height + 10 ; // 距离父视图也变化
      button.
frame = CGRectMake ( 10 + w, h, length + 15 , 30 ); // 重设 button frame
    }
      w = button.
frame . size . width + button. frame . origin . x ;
      [
self . view addSubview :button];
}
 



原文:http://blog.csdn.net/duoduo_333/article/details/47024551

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值