iOS UILabel根據字符串長度自動適應寬度和高度

    //這個frame是初設的,不要緊,後面還會從新設置其size。
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor clearColor];
    
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20],};
    
    NSString *str = @"abcdefg你上課但是你的拿到了";
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
    
    [label setFrame:CGRectMake(100, 100, textSize.width, textSize.height)];
    label.textColor = [UIColor greenColor];
    label.text = str;
    [self.view addSubview:label];
相關文章
相關標籤/搜索