Adjust UILabel height depending on the text

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

    Here is a category version:

    UILabel+AutoSize.h #import

    @interface UILabel (AutoSize)
    
    - (void) autosizeForWidth: (int) width;
    
    @end
    

    UILabel+AutoSize.m

    #import "UILabel+AutoSize.h"
    
    @implementation UILabel (AutoSize)
    
    - (void) autosizeForWidth: (int) width {
        self.lineBreakMode = UILineBreakModeWordWrap;
        self.numberOfLines = 0;
        CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
        CGSize expectedLabelSize = [self.text sizeWithFont:self.font constrainedToSize:maximumLabelSize lineBreakMode:self.lineBreakMode];
        CGRect newFrame = self.frame;
        newFrame.size.height = expectedLabelSize.height;
        self.frame = newFrame;
    }
    
    @end
    

提交回复
热议问题