且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UILabel具有固定的宽度和灵活的高度

更新时间:2022-03-08 09:25:25

我喜欢子类 UILabel 为我这样做。

I like to subclass UILabel to do this for me.

AutosizingLabel.h

AutosizingLabel.h

#import <UIKit/UIKit.h>


@interface AutosizingLabel : UILabel {
    double minHeight;
}

@property (nonatomic) double minHeight;

- (void)calculateSize;

@end    

AutosizingLabel.m

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

要使用此功能,请导入/在项目中创建.h和.m文件。然后,如果您在代码中创建 UILabel ,它将如下所示:

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];
}

如果你正在使用XIB,你可以选择任何UILabel并点击右侧边栏中的Identity Inspector将其类设置为 AutosizingLabel 。在任何一种情况下,设置 .text 属性都会自动更新标签的大小。

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.