iPhone - Adjust UILabel width according to the text

后端 未结 7 1545
天涯浪人
天涯浪人 2020-12-28 08:17

How can I adjust the label Width according to the text? If text length is small I want the label width small...If text length is small I want the label width according to th

相关标签:
7条回答
  • 2020-12-28 09:07

    sizeWithFont constrainedToSize:lineBreakMode: is the original method to use. Here is an example of how to use it is below:

    //Calculate the expected size based on the font and linebreak mode of your label
    CGSize maximumLabelSize = CGSizeMake(296,9999);
    
    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;
    
    0 讨论(0)
提交回复
热议问题