ios - 在单行 UILabel 旁边居中 NSTextAttachment 图像

标签 ios objective-c swift uilabel nstextattachment

我想将 NSTextAttachment 图像附加到我的属性字符串并使其垂直居中。

我使用以下代码来创建我的字符串:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:DDLocalizedString(@"title.upcomingHotspots") attributes:attrs];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage imageNamed:@"help.png"] imageScaledToFitSize:CGSizeMake(14.f, 14.f)];
cell.textLabel.attributedText = [str copy];

但是,图像似乎与单元格 textLabel 的顶部对齐。

text attachment offset problem screenshot

如何更改绘制附件的矩形?

最佳答案

您可以使用字体的 capHeight。

Objective-C

NSTextAttachment *icon = [[NSTextAttachment alloc] init];
UIImage *iconImage = [UIImage imageNamed:@"icon.png"];
[icon setBounds:CGRectMake(0, roundf(titleFont.capHeight - iconImage.size.height)/2.f, iconImage.size.width, iconImage.size.height)];
[icon setImage:iconImage];
NSAttributedString *iconString = [NSAttributedString attributedStringWithAttachment:icon];
[titleText appendAttributedString:iconString];

swift

let iconImage = UIImage(named: "icon.png")!
var icon = NSTextAttachment()
icon.bounds = CGRect(x: 0, y: (titleFont.capHeight - iconImage.size.height).rounded() / 2, width: iconImage.size.width, height: iconImage.size.height)
icon.image = iconImage
let iconString = NSAttributedString(attachment: icon)
titleText.append(iconString)

附件图像呈现在文本的基线上。 并且它的y轴像核心图形坐标系一样反转。 如果要向上移动图像,请将 bounds.origin.y 设置为正数。

图像应与文本的 capHeight 垂直居中对齐。 所以我们需要将 bounds.origin.y 设置为 (capHeight - imageHeight)/2

为了避免对图像产生一些锯齿状的影响,我们应该对 y 的小数部分进行四舍五入。但是字体和图像通常很小,即使是 1px 的差异也会使图像看起来像错位。所以我在划分之前应用了round函数。它将 y 值的小数部分设为 .0 或 .5

在您的情况下,图像高度大于字体的 capHeight。但是你可以用同样的方法。偏移 y 值将为负数。并且会从基线的下方开始布局。

enter image description here

引用资料:

苹果开发者 Text Programming Guide for iOS

关于ios - 在单行 UILabel 旁边居中 NSTextAttachment 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26105803/

相关文章:

swift - Xcode 7 从 XCUIElement 转换为无关类型 'String' 在获取 JSON 时总是失败

ios - 交互式过渡 : Segue declaration

ios - phonegap-push-plugin 在 iOS 中不起作用

ios - Xcode Assets 目录 : Only one copy of each image

ios - 无法识别的选择器发送到类 0x865c6c

iphone - 尝试将字符串转换为日期

ios - CoreML : "Unexpected error processing model" error sometimes occurring

ios - 如何知道从另一个 View Controller 中的 UICollectionViewController 按下了哪个按钮

objective-c - 使用 OpenGL-ES 在 iOS 上播放视频

objective-c - 如何从 Kal 控件中获取选定的日期?