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

标签 ios swift uikit

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

Short text example

Large text example

现在,我只是放置一个全角标签,在运行时,我使用 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

输出:

enter image description here

关于ios - 在 iOS 上将图像和文本内联居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31183030/

相关文章:

iphone - 访问上次收到的已关闭/忽略的推送通知

ios - Swift - 如何从具有 String 属性的对象数组创建字符串?

ios - 将长字符串设置为 UILabel 卡住我的应用程序并出现未检测到的错误

ios - 捕获了 UIBarButtonItem 的 Action

ios - 在 UIView 子类中实现 UIResponder 触摸方法是否违反了 MVC?

ios - 从我的应用程序打开电子邮件

ios - 联系电话保持为零

ios - UICollectionView cellForItem(在 :) crashes

ios - 未调用 ELCImagePickerController 委托(delegate)方法

swift - 有没有办法找出 Xcode 构建哪些文件需要很长时间?