UIButton自适应及自动换行(笨鸟先飞一)

图片发自简书App



NSArray *Arr = @[@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"够了没有呢",@"哎 还是多写几个吧",@"丰富特权",@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"够了没有呢",@"哎 还是多写几个吧",@"丰富特权"];

//创建各个Button

NSInteger currentRight = 0; // 记录当前Btn的right(右边)

NSInteger currentBotton = 0; // 记录当前btn的bottom(底部)

for (int i = 0; i < Arr.count; i++)

{

UIButton *Btn=[UIButton buttonWithType:UIButtonTypeCustom];

Btn.frame = CGRectMake(currentRight + 15, currentBotton + 30, 80, 25);

// 计算字体长度

CGSize size = [Arr[i]  boundingRectWithSize:CGSizeMake(200, 30000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;

// 更新btn的右边

currentRight = currentRight + size.width + 40;

// 判断是否换行

if (i < Arr.count - 1)

{

NSString *str = Arr[i + 1];

// 计算字体长度

CGSize size = [str  boundingRectWithSize:CGSizeMake(200, 30000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;

if (currentRight + size.width > SCREEN_WIDTH - 60)

{

currentRight = 0;

currentBotton = currentBotton + 45;

}

}

// 更新每个Btn的frame

CGRect frame = CGRectMake(Btn.frame.origin.x, Btn.frame.origin.y, size.width + 30, size.height +20);

Btn.frame = frame;

// 设置btn的属性

Btn.titleLabel.font=[UIFont systemFontOfSize:13];

Btn.backgroundColor=[UIColor clearColor];

[Btn setTitleColor:[UIColor colorWithRed:69/255.0 green:69/255.0 blue:68/255.0 alpha:1.0] forState:UIControlStateNormal];

[Btn setTitle:Arr[i] forState:UIControlStateNormal];

Btn.titleLabel.adjustsFontSizeToFitWidth = YES;

Btn.layer.cornerRadius=5;

Btn.layer.borderColor=[UIColor lightGrayColor].CGColor;

Btn.layer.borderWidth=0.7;

Btn.layer.masksToBounds=YES;

[self.view addSubview:Btn];

}

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

推荐阅读更多精彩内容

  • Quartz2D以及drawRect的重绘机制字数1487 阅读21 评论1 喜欢1一、什么是Quartz2D Q...
    PurpleWind阅读 830评论 0 3
  • 一:实现效果 二:实现思路 1:配置参数添加到ViewController - (void)viewDidLoad...
    欧大帅Allen阅读 1,697评论 0 4
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,155评论 1 6
  • 中国房地产的三大里程碑 1.1994年《关于深化城镇住房制度改革的决定》 后期经过了 许多完善 1998年,a.取...
    穆青玄阅读 1,864评论 0 0
  • 雨过云出晴方好,娇花怒放鸟儿早, 片片青叶引人朝,暗郁华阴入胜境, 独倚西楼读词了。小园香径何人晓。 其二 独倚西...
    纳兰容若123阅读 245评论 0 2