美文网首页
iOS根据UIlabel的内容动态设置高度

iOS根据UIlabel的内容动态设置高度

作者: 三岁就很乖 | 来源:发表于2020-01-08 22:30 被阅读0次
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //根据内容自动调整高度
    
    NSString *str = @"人各有异,这是一种幸运:一个个风格迥异的人,构成了我们所能体会的丰富世界,但人本质上又那么一致,这也是幸运:如果有心,便能通过这共同的部分,最终看见彼此,映照出彼此,温暖彼此。就像维摩诘说:“是身如幻,从颠倒起,是身如影,从业缘现,是身如焰,从渴望生。”皮囊众生百相,这个世界是由一个个奇特的皮囊组成,而皮囊下包裹的心,正是生命的本相。我们生命本来是轻盈的,所以,别再让你的灵魂被皮囊裹挟住,皮囊是拿来用的,不是拿来伺候的。";
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 8;//调整行间距 这个跟计算高度的行间距一定要对应
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    UIFont *systemFont = [UIFont systemFontOfSize:25.0f];
    
    [attributedString addAttribute:NSFontAttributeName value:systemFont range:NSMakeRange(0, [str length])];
    
    
  //  NSDictionary *attributes = @{@"NSFontAttributeName":systemFont,@"NSParagraphStyleAttributeName":paragraphStyle};
    
    CGSize size = CGSizeMake(self.view.frame.size.width-20,2000);
    
    CGSize lastSize= [attributedString boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine) context:nil].size;

//    CGRect labelRect = [attributedString boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
//
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10,100,self.view.frame.size.width-20, lastSize.height)];
    
    label.backgroundColor=[UIColor redColor];
    label.numberOfLines=0;
    label.attributedText = attributedString;
    [self.view addSubview: label];
}

相关文章

网友评论

      本文标题:iOS根据UIlabel的内容动态设置高度

      本文链接:https://www.haomeiwen.com/subject/uzleactx.html