ios 动态尺寸标签 [英] ios Dynamic sizing labels

查看:23
本文介绍了ios 动态尺寸标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

非常感谢任何建议.

推荐答案

你可以计算你的字符串将出现的大小,然后可以将你的 UILabel 的框架设置为该大小,请参阅以下代码作为示例 -

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 -

//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 和您的字体对象的配对,如下所示:

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

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

检查 是否替换已弃用的 sizeWithFont:在 iOS 7 中?更多详情

这篇关于ios 动态尺寸标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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