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

查看:85
本文介绍了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.

任何建议都将不胜感激.

Any advice is greatly appreciated.

推荐答案

您可以计算将在其中显示字符串的大小,然后可以将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天全站免登陆