Adjust UILabel height depending on the text

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

    Finally, it worked. Thank you guys.

    I was not getting it to work because i was trying to resize the label in heightForRowAtIndexPath method:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    

    and (yeah silly me), i was resizing the label to default in cellForRowAtIndexPath method - i was overlooking the code i had written earlier:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    
    0 讨论(0)
  • 2020-11-22 04:22
    NSString *str = @"Please enter your text......";
    CGSize lblSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize: CGSizeMake(200.0f, 600.0f) lineBreakMode: NSLineBreakByWordWrapping];
    
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(60, 20, 200, lblSize.height);
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = [UIFont systemFontOfSize:15];
    label.text = str;
    label.backgroundColor = [UIColor clearColor];
    [label sizeToFit];
    [self.view addSubview:label];
    
    0 讨论(0)
  • 2020-11-22 04:23

    Solution to iOS7 prior and iOS7 above

    //
    //  UILabel+DynamicHeight.m
    //  For StackOverFlow
    //
    //  Created by Vijay on 24/02/14.
    //  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
    
    #define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
    
    #define iOS7_0 @"7.0"
    
    @interface UILabel (DynamicHeight)
    
    /*====================================================================*/
    
    /* Calculate the size,bounds,frame of the Multi line Label */
    
    /*====================================================================*/
    /**
     *  Returns the size of the Label
     *
     *  @param aLabel To be used to calculte the height
     *
     *  @return size of the Label
     */
    
    -(CGSize)sizeOfMultiLineLabel;
    
    @end
    
    
    //
    //  UILabel+DynamicHeight.m
    //  For StackOverFlow
    //
    //  Created by Vijay on 24/02/14.
    //  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
    //
    
    #import "UILabel+DynamicHeight.h"
    
    @implementation UILabel (DynamicHeight)
    /*====================================================================*/
    
    /* Calculate the size,bounds,frame of the Multi line Label */
    
    /*====================================================================*/
    /**
     *  Returns the size of the Label
     *
     *  @param aLabel To be used to calculte the height
     *
     *  @return size of the Label
     */
    -(CGSize)sizeOfMultiLineLabel{
    
        NSAssert(self, @"UILabel was nil");
    
        //Label text
        NSString *aLabelTextString = [self text];
    
        //Label font
        UIFont *aLabelFont = [self font];
    
        //Width of the Label
        CGFloat aLabelSizeWidth = self.frame.size.width;
    
    
        if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
            //version < 7.0
    
            return [aLabelTextString sizeWithFont:aLabelFont
                                constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                    lineBreakMode:NSLineBreakByWordWrapping];
        }
        else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
            //version >= 7.0
    
            //Return the calculated size of the Label
            return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{
                                                            NSFontAttributeName : aLabelFont
                                                            }
                                                  context:nil].size;
    
        }
    
        return [self bounds].size;
    
    }
    
    @end
    
    0 讨论(0)
  • 2020-11-22 04:23

    Thanks for this post. It helped me a great deal. In my case I am also editing the text in a separate view controller. I noticed that when I use:

    [cell.contentView addSubview:cellLabel];
    

    in the tableView:cellForRowAtIndexPath: method that the label view was continually rendered over the top of the previous view each time I edited the cell. The text became pixelated, and when something was deleted or changed, the previous version was visible under the new version. Here's how I solved the problem:

    if ([[cell.contentView subviews] count] > 0) {
        UIView *test = [[cell.contentView subviews] objectAtIndex:0];
        [test removeFromSuperview];
    }
    [cell.contentView insertSubview:cellLabel atIndex:0];
    

    No more weird layering. If there is a better way to handle this, Please let me know.

    0 讨论(0)
  • 2020-11-22 04:23

    You may use it as a method, as well. @Pyjamasam is very much true so i am just making its method. It may be helpfull for some one else

    -(CGRect)setDynamicHeightForLabel:(UILabel*)_lbl andMaxWidth:(float)_width{
        CGSize maximumLabelSize = CGSizeMake(_width, FLT_MAX);
    
        CGSize expectedLabelSize = [_lbl.text sizeWithFont:_lbl.font constrainedToSize:maximumLabelSize lineBreakMode:_lbl.lineBreakMode];
    
        //adjust the label the the new height.
        CGRect newFrame = _lbl.frame;
        newFrame.size.height = expectedLabelSize.height;
        return newFrame;
    }
    

    and just set it like this

    label.frame = [self setDynamicHeightForLabel:label andMaxWidth:300.0];
    
    0 讨论(0)
  • 2020-11-22 04:24

    One line is Chris's answer is wrong.

    newFrame.size.height = maximumLabelSize.height;
    

    should be

    newFrame.size.height = expectedLabelSize.height;
    

    Other than that, it's the correct solution.

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