UILabel具有固定的宽度和灵活的高度 [英] UILabel with fixed width and flexible height

查看:182
本文介绍了UILabel具有固定的宽度和灵活的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Detail View Controller中有一个UILabel,因此其内容会根据所选的表行而改变。我有一个问题,我会为我的UILabel设置一个固定的宽度,并根据文本设置动态高度。我怎样才能做到这一点? (我很抱歉我的错误,但我不是英文)

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 dynamic height depending on the text. How can I do this? (I'm sorry for my mistakes, but I'm not English)

推荐答案

我喜欢子类 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.

这篇关于UILabel具有固定的宽度和灵活的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆