在iOS上内嵌图像和文本

时间:2015-07-02 11:14:09

标签: ios swift uikit

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

Short text example

Large text example

现在,我只是放了一个全角标签,在运行时,我用navigationDrawer.setDrawerShadow(R.drawable.someDrawable,GravityCompat.Start); 方法测量文本宽度,并以编程方式调整我的图像约束。

您是否有任何好主意在不手动测量文字宽度的情况下构建此类界面?

2 个答案:

答案 0 :(得分: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;

夫特

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

输出:

enter image description here

答案 1 :(得分:1)

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

enter image description here

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

大多数带代码的Unicode符号可以在http://unicode-table.com/

找到