ios 动态尺寸标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9181368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:41:49  来源:igfitidea点击:

ios Dynamic sizing labels

iostextuilabelfont-size

提问by Seb

I've tried to search online, but haven't found a clear answer for my issue so I've come to ask for your expert advice. I have a view with 2 labels on it. The first label is used to show an abbreviation of a name, 2-3 letters. and the second label shows the full name.

我试图在网上搜索,但没有找到我的问题的明确答案,所以我来寻求您的专家建议。我有一个视图,上面有 2 个标签。第一个标签用于显示名称的缩写,2-3 个字母。第二个标签显示全名。

The question that I have is if there was a way to dynamically size the label based on the font type, size, and string length given? I ask because I would like the second label close to the first without too much empty space between the two or without the first label overlapping the second.

我的问题是是否有办法根据给定的字体类型、大小和字符串长度动态调整标签大小?我问是因为我希望第二个标签靠近第一个标签,两者之间没有太多空白空间,或者第一个标签不与第二个标签重叠。

The reason that this isn't all in one label is because the first label should have a bigger font and different color scheme then the second label.

这不是全部在一个标签中的原因是因为第一个标签应该具有比第二个标签更大的字体和不同的配色方案。

Any advice is greatly appreciated.

任何意见是极大的赞赏。

回答by Saurabh

You can calculate the size of in which your string will appear and then can set frame of your UILabel to that size see following code as a sample -

您可以计算字符串将出现的大小,然后可以将 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;

Update -

更新 -

Use sizeWithAttributes:instead, which now takes an NSDictionary. Pass in the pair with key UITextAttributeFontand your font object like this:

使用sizeWithAttributes:相反,现在需要的NSDictionaryUITextAttributeFont像这样传递带有键和字体对象的配对:

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

Check Replacement for deprecated sizeWithFont: in iOS 7?for more details

检查替换是否已弃用 sizeWithFont: 在 iOS 7 中?更多细节

回答by noRema

This will also do the trick and will take into account attributed text

这也可以解决问题,并将考虑属性文本

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;

回答by schirrmacher

'sizeWithFont:' is deprecated: first deprecated in iOS 7.0.

'sizeWithFont:' 已弃用:首先在 iOS 7.0 中弃用。

so try sizeWithAttributes

所以试试 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];
}

回答by eduludi

As sizeWithFont:is deprecated in iOS 7, you need to use sizeWithAttributes(as maver explained here). In order to simplify code, you can add a method that you can reuse like this:

由于sizeWithFont:在 iOS 7 中已弃用,您需要使用sizeWithAttributes(如 maver 解释here)。为了简化代码,您可以添加一个可以重复使用的方法,如下所示:

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

And make use of it

并利用它

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

回答by Slavcho

In addition of Saurabh's answer. I had the same problem and you should add this line
[yourLabel setNumberOfLines:0];
in order the whole text to be shown in X lines.

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