Adjust UILabel height depending on the text

前端 未结 30 2186
走了就别回头了
走了就别回头了 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条回答
  •  萌比男神i
    2020-11-22 04:29

    sizeWithFont constrainedToSize:lineBreakMode: is the method to use. An example of how to use it is below:

    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
    
    CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   
    
    //adjust the label the the new height.
    CGRect newFrame = yourLabel.frame;
    newFrame.size.height = expectedLabelSize.height;
    yourLabel.frame = newFrame;
    

提交回复
热议问题