Adjust UILabel height depending on the text

前端 未结 30 2191
走了就别回头了
走了就别回头了 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:13

    This method will give perfect height

    -(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
    CGSize constraint = CGSizeMake(width , 20000.0f);
    CGSize title_size;
    float totalHeight;
    
    
    title_size = [text boundingRectWithSize:constraint
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{ NSFontAttributeName : font }
                                    context:nil].size;
    
    totalHeight = ceil(title_size.height);
    
    CGFloat height = MAX(totalHeight, 40.0f);
    return height;
    }
    

提交回复
热议问题