UILabel auto resize on basis of text to be shown

后端 未结 10 1889
余生分开走
余生分开走 2021-01-29 22:44

I\'m working on an application, in which I\'m required to autoresize the text area on basis of text to be displayed.

Firstly, I\'m not sure for this either I should use

相关标签:
10条回答
  • 2021-01-29 23:20

    In Swift:

    testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
    testLabel.text = test
    testLabel.numberOfLines = 0
    testLabel.sizeToFit()
    

    In Objective C

    UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
    testLabel.text = test;
    testLabel.numberOfLines = 0;
    [testLabel sizeToFit];
    
    0 讨论(0)
  • 2021-01-29 23:20

    I'm not sure I totally understand the question, but you can use the sizeToFit method on a UILabel (the method is inherited from UIView) to change the size according to the label text.

    0 讨论(0)
  • 2021-01-29 23:20

    The easiest way to find the no. of lines depending on text. You can use this code:

    ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 
    

    it returns some float value.

    [lbl setNumberOfLines:floatvalue];
    
    0 讨论(0)
  • 2021-01-29 23:24

    Please note that with autolayout call sizeToFit won't change size, because it will be changed later by autolayout calculations. In this case you need to setup proper height constraint for your UILabel with "height >= xx" value.

    0 讨论(0)
  • 2021-01-29 23:26

    You can find a text size with :

    CGSize textSize = [[myObject getALongText] 
                        sizeWithFont:[UIFont boldSystemFontOfSize:15] 
                        constrainedToSize:CGSizeMake(maxWidth, 2000)
                        lineBreakMode:UILineBreakModeWordWrap];
    

    then you can create your UILabel like that :

    UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];
    [lbl setNumberOfLines:0];
    [lbl setLineBreakMode:UILineBreakModeWordWrap];
    [lbl setText:[myObject getALongText]];
    
    0 讨论(0)
  • 2021-01-29 23:33

    If you want to resize the UILabel only in height, use this:

    @property (nonatomic, weak) IBOutlet UILabel *titleLabel;
    
    CGRect titleLabelBounds = self.titleLabel.bounds;
    titleLabelBounds.size.height = CGFLOAT_MAX;
    // Change limitedToNumberOfLines to your preferred limit (0 for no limit)
    CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2];
    
    CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height;
    CGRect titleFrame = self.titleLabel.frame;
    titleFrame.size.height += titleLabelHeightDelta;
    self.titleLabel.frame = titleFrame;
    

    Now you can use titleLabelHeightDelta to layout other views depending on your label size (without using autolayout).

    0 讨论(0)
提交回复
热议问题