在 iOS 上将内联图像和文本居中

Center both image and text inline on iOS

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

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

在不手动测量文本宽度的情况下构建这种界面有什么好主意吗?

Objective - 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

输出:

@ashish-kakkad 的回答很完美,但除非您需要像素完美的图像,否则您可以使用 Unicode 符号:

[self.button1 setTitle:@"\u27A4 Button" forState:UIControlStateNormal];

大多数带有代码的 Unicode 符号都可以在这里找到http://unicode-table.com/