Adjust UILabel height depending on the text

前端 未结 30 2160
走了就别回头了
走了就别回头了 2020-11-22 03:53

Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players m

30条回答
  •  时光取名叫无心
    2020-11-22 04:28

    Since sizeWithFont is deprecated I use this one instead.

    this one get label specific attributes.

    -(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{
    
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    
        return ceil(rect.size.height);
    }
    

提交回复
热议问题