iOS动态调整标签大小

28

我已经尝试在网上搜索,但没有找到关于我的问题的明确答案,所以我来寻求您的专业建议。我有一个视图,其中包含2个标签。第一个标签用于显示姓名的缩写,通常是2-3个字母,第二个标签显示完整的姓名。

我的问题是是否有一种方法可以根据给定的字体类型、大小和字符串长度动态调整标签的大小?我之所以问这个问题,是因为我想让第二个标签靠近第一个标签,而两者之间不要有太多空白间隔,也不要让第一个标签与第二个标签重叠。

这个原因是因为第一个标签应该有一个比第二个标签更大的字体和不同的颜色方案。

非常感谢您的任何建议。


请点击此链接rob mayoff的答案谢谢。 - umakanta
5个回答

64
你可以计算出字符串所需的大小,然后设置UILabel的框架大小为该大小,请参考以下示例代码 -
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

更新 -

现在可以使用 sizeWithAttributes:,该方法接受一个 NSDictionary。将键值对传递给字典,其中键为 UITextAttributeFont,值为您的字体对象,代码如下:

CGSize size = [string sizeWithAttributes:
                       @{NSFontAttributeName:
                         [UIFont systemFontOfSize:17.0f]}];

请查看iOS 7中已弃用的sizeWithFont:方法的替代方案?以获取更多详细信息。


1
您真是个救星。我还在努力学习iOS API以及一切应该如何工作的知识。 - Seb
@Seb - 祝你好运!编程愉快! - Saurabh
这段代码:lineBreakMode:yourLabel.lineBreakMode 不适用于IOS 6。 - Nazir
sizeWithFont已经被弃用。有没有好的替代方案,最好能提供示例? - shashwat

16

这也能解决问题,并且会考虑到带属性的文本

label.attributedText = attrString;
CGSize maximumLabelSize = CGSizeMake(187,CGFLOAT_MAX);
CGSize requiredSize = [label sizeThatFits:maximumLabelSize];
CGRect labelFrame = label.frame;
labelFrame.size.height = requiredSize.height;
label.frame = labelFrame;

这个解决方案更加合理。UILabel 应该负责大小,而不是 NSString - Berik
什么是 CGFLOAT_MAX - swiftBoy
它是浮点变量可以存储的最高值。 - noRema
attrString 的替代内容会是什么? - Ahmad Gulzar

10

'sizeWithFont:' 已经被弃用:自 iOS 7.0 开始已经过时。

因此请尝试使用 sizeWithAttributes

- (void)viewDidLoad
{
    [super viewDidLoad];

    label = [[UILabel alloc] initWithFrame:CGRectMake(20, 40, 300, 20)];

    label.backgroundColor = [UIColor blueColor];

     const CGFloat fontSize = 30;
     UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
     UIColor *foregroundColor = [UIColor blackColor];

     attrs = [NSDictionary dictionaryWithObjectsAndKeys:
     regularFont, NSFontAttributeName,
     foregroundColor, NSForegroundColorAttributeName
     , nil];

     NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
     initWithString:@"Test Text"
     attributes:attrs];

     [label setAttributedText:attributedText];
     [self.view addSubview:label];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGSize expectedLabelSize = [label.text sizeWithAttributes:attrs]; // iOS 7 Code <--

    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
                                                 initWithString:@"Longer Test Text"
                                                 attributes:attrs];

    [label setAttributedText:attributedText];
}

8

sizeWithFont:在iOS 7中已经被弃用,你需要使用sizeWithAttributes(正如maver在这里所解释的那样)。为了简化代码,你可以添加一个可重复使用的方法,具体如下:

-(CGRect)rectForText:(NSString *)text 
           usingFont:(UIFont *)font 
       boundedBySize:(CGSize)maxSize
{
    NSAttributedString *attrString =
        [[NSAttributedString alloc] initWithString:text
                                        attributes:@{ NSFontAttributeName:font}];

    return [attrString boundingRectWithSize:maxSize
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                    context:nil];
}

并且充分利用它。

CGSize maximumLabelSize = CGSizeMake(280,9999);
UIFont *font = [UIFont systemFontOfSize:20];
CGRect titleRect = [self rectForText:post.title // <- your text here 
                           usingFont:font
                       boundedBySize:maximumLabelSize];

7
除了Saurabh的回答之外,我也遇到了同样的问题。你应该添加这一行:
[yourLabel setNumberOfLines:0];
以便整个文本可以在X行中显示。

是的,在将numberOfLines设置为0之后,我的问题得到了解决,否则我在实现Saurabh的解决方案时会一直撞头。 - Ans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接