在iOS上内嵌图像和文本

swe*_*py_ 5 uikit ios swift

我有一个全角标签,带有动态文本,因此可以是两个字符或十个字符.我需要在左侧部分内嵌显示图像,始终与第一个字母相距10px.请参阅下面的示例.

简短的文字示例

大文本示例

现在,我只是放了一个全角标签,在运行时,我用boundingRectWithSize:方法测量文本宽度,并以编程方式调整我的图像约束.

你有没有任何好主意建立这种界面而不用手动测量文字宽度?

Ash*_*kad 8

目标 - C.

您可以将图像添加为文本附件.

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *imageTest=[UIImage imageNamed:@"arrow.png"];
attachment.image = imageTest;
NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text "];
NSMutableAttributedString *myStringWithArrow = [[NSMutableAttributedString alloc]initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
[myStringWithArrow appendAttributedString:myString];
yourLabel.attributedText = myStringWithArrow;
Run Code Online (Sandbox Code Playgroud)

迅速

var attachment = NSTextAttachment()
var imageTest = UIImage(named:"arrow.png")
attachment.image = imageTest
var myString = NSMutableAttributedString(string: "My label text ")
var myStringWithArrow = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
myStringWithArrow.appendAttributedString(myString)
lblAttributed.attributedText = myStringWithArrow
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述