iOS - UIButton大小随文本自适应及换行(笨鸟先飞中)

时间:2024-04-04 22:44:00

iOS - UIButton大小随文本自适应及换行(笨鸟先飞中)

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=[UIButtonbuttonWithType:UIButtonTypeCustom];

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

        

        // 计算字体长度

        CGSize size = [Arr[i] boundingRectWithSize:CGSizeMake(200,30000)options:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize: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:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize: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=[UIFontsystemFontOfSize:13];

        Btn.backgroundColor=[UIColorclearColor];

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

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

        Btn.titleLabel.adjustsFontSizeToFitWidth = YES;

        Btn.layer.cornerRadius=5;

        Btn.layer.borderColor=[UIColorlightGrayColor].CGColor;

        Btn.layer.borderWidth=0.7;

        Btn.layer.masksToBounds=YES;

        [self.viewaddSubview:Btn];

    }