Adjust UILabel height depending on the text

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

    In iOS 6 Apple has added a property to UILabel that greatly simplifies dynamic vertical resizing of labels: preferredMaxLayoutWidth.

    Using this property in combination with lineBreakMode = NSLineBreakByWordWrapping and sizeToFit method allows easily resize a UILabel instance to the height that accommodates the entire text.

    A quote from iOS documentation:

    preferredMaxLayoutWidth The preferred maximum width (in points) for a multiline label.

    Discussion This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text is flowed to one or more new lines, thereby increasing the height of the label.

    A sample:

    ...
    UILabel *status = [[UILabel alloc] init];
    status.lineBreakMode = NSLineBreakByWordWrapping;
    status.numberOfLines = 5; // limits to 5 lines; use 0 for unlimited.
    
    [self addSubview:status]; // self here is the parent view
    
    status.preferredMaxLayoutWidth = self.frame.size.width; // assumes the parent view has its frame already set.
    
    status.text = @"Some quite lengthy message may go here…";
    [status sizeToFit];
    [status setNeedsDisplay];
    ...
    

提交回复
热议问题