UILabel with fixed width and flexible height

前端 未结 2 967
旧巷少年郎
旧巷少年郎 2021-02-09 05:26

I\'ve got an UILabel in a Detail View Controller, so its content changes depending on the selected table row. I have a problem, I would set a fixed width for my UILabel and a dy

相关标签:
2条回答
  • 2021-02-09 06:04

    I like to subclass UILabel to do this for me.

    AutosizingLabel.h

    #import <UIKit/UIKit.h>
    
    
    @interface AutosizingLabel : UILabel {
        double minHeight;
    }
    
    @property (nonatomic) double minHeight;
    
    - (void)calculateSize;
    
    @end    
    

    AutosizingLabel.m

    #define MIN_HEIGHT 10.0f
    
    #import "AutosizingLabel.h"
    
    @implementation AutosizingLabel
    
    @synthesize minHeight;
    
    - (id)init {
        if ([super init]) {
            self.minHeight = MIN_HEIGHT;
        }
    
        return self;
    }
    
    - (void)calculateSize {
        CGSize constraint = CGSizeMake(self.frame.size.width, 20000.0f);
        CGSize size = [self.text sizeWithFont:self.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];    
    
        [self setLineBreakMode:UILineBreakModeWordWrap];
        [self setAdjustsFontSizeToFitWidth:NO];
        [self setNumberOfLines:0];
        [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, MAX(size.height, MIN_HEIGHT))];
    
    }
    
    - (void)setText:(NSString *)text {  
        [super setText:text];
    
        [self calculateSize];
    }
    
    - (void)setFont:(UIFont *)font {
        [super setFont:font];
    
        [self calculateSize];
    }
    
    @end
    

    To use this, import/create the .h and .m files in your project. Then if you are creating your UILabel in code, it would look something like this:

    #import "AutosizingLabel.h"
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        AutosizingLabel *label = [[AutosizingLabel alloc] init];
        label.text = @"Some text here";
        [self.view addSubview:label];
    }
    

    If you're using a XIB, you can select any UILabel and click on the Identity Inspector in the right sidebar to set it's class to AutosizingLabel. In either case, setting the .text property will auto update the size of the label.

    0 讨论(0)
  • 2021-02-09 06:11

    You can do it ..here is code.

    UILabel *yourlabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 100, sizeToFit)];
    yourlabel.numberOfLines = 0;
    

    For Any Query please comment.

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