如何在iOS中根据文本长度更改UILabel宽度? [英] How to change UILabel width based on text length in iOS?

查看:43
本文介绍了如何在iOS中根据文本长度更改UILabel宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在"UILabel"旁边显示图像,但是"UILabel"具有可变的文本长度,因此我不知道将图像放置在何处.

I want to display an image next to a 'UILabel', however 'UILabel' has variable text length, so I don't know where to place the image.

图像应根据标签的大小移动.

Image should move according to the size of the label.

我该怎么做?

推荐答案

尽管Keshav的答案可行,但已弃用

Although Keshav answer will work, it's deprecated

尝试:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};

CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];

然后使用矩形的大小确定您的位置和标签大小.

Then use the Size of rect to determine your positioning and label size.

CGRect currentLabelFrame = self.label.frame;

currentLabelFrame.size.width = rect.size.width;

self.label.frame = currentLabelFrame;

这篇关于如何在iOS中根据文本长度更改UILabel宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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