iOS 多个label/button自动换行

2,519 阅读2分钟

写在前面

最近在做公司的项目,里面用到了评价标签自动换行的功能,网上查了下有一些第三方的控件,但是感觉不是很合适,所以自己写了一个,练手&&强化记忆,不啰嗦了,下面是具体代码实现

代码实现

//调用
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *str = @"永和九年,岁在癸丑,暮春之初,会于会稽山阴之兰亭,修禊事也。群贤毕至,少长咸集。此地有崇山峻岭,茂林修竹,又有清流激湍,映带左右,引以为流觞曲水,列坐其次。虽无丝竹管弦之盛,一觞一咏,亦足以畅叙幽情";
    NSArray *titleArr = [str componentsSeparatedByString:@","];
    [self createLabelWithArray:titleArr FontSize:14 SpcX:20 SpcY:30];
}

//动态添加label方法
- (void)createLabelWithArray:(NSArray *)titleArr FontSize:(CGFloat)fontSize SpcX:(CGFloat)spcX SpcY:(CGFloat)spcY
{
    //创建tag值的View
    UIView *tagView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, 320, 200)];
    tagView.backgroundColor = [UIColor greenColor];
    //创建标签位置变量
    CGFloat positionX = spcX;
    CGFloat positionY = spcY;
    //临界值判断变量
    CGFloat bgViewWidth = tagView.frame.size.width;
    //创建label
    for(int i = 0; i < titleArr.count; i++)
    {
        CGSize labelSize = [self getSizeByString:titleArr[i] AndFontSize:fontSize];
        CGFloat labelWidth = labelSize.width;
        if(positionX + labelWidth > bgViewWidth)
        {
            positionX = spcX;
            positionY += spcY;
        }
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(positionX, positionY, labelWidth, 24)];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.text = titleArr[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.masksToBounds = YES;
        label.layer.cornerRadius = 12;
        label.layer.borderWidth = 1;
        label.layer.borderColor = [UIColor blackColor].CGColor;
        
        positionX += (labelWidth + 5);
        [tagView addSubview:label];
    }
    [self.view addSubview:tagView];
}
//获取字符串长度的方法
- (CGSize)getSizeByString:(NSString*)string AndFontSize:(CGFloat)font
{
    CGSize size = [string boundingRectWithSize:CGSizeMake(999, 25) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    size.width += 5;
    return size;
}