我有一个全角标签,带有动态文本,因此它可以是两个或十个字符。我需要在左侧部分内联显示图像,始终距离第一个字母 10px。请参阅下面的示例。
现在,我只是放置一个全角标签,在运行时,我使用 boundingRectWithSize:
方法测量文本宽度,并以编程方式调整我的图像约束。
在不手动测量文本宽度的情况下构建这种界面有什么好主意吗?
最佳答案
目标 - 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;
swift
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
输出:
关于ios - 在 iOS 上将图像和文本内联居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31183030/