ios - 在单行 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 的顶部对齐。

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

最佳答案

您可以使用字体的 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 值将为负数。并且会从基线的下方开始布局。

引用资料:

苹果开发者 Text Programming Guide for iOS

https://stackoverflow.com/questions/26105803/

相关文章:

ios - UICollectionViewCell 上的长按手势

ios - 设置 UILabel 行距

ios - UICollectionView 当前可见单元格索引

objective-c - iOS8 - 约束含糊地暗示高度为零

ios - 对 UITableView 使用 didSelectRowAtIndexPath 或 p

objective-c - iOS 7.0.3 上的 "HelveticaNeue-Italic"发

ios - "From View Controller"使用 UIViewControllerCon

ios - 带有透明孔的 CALayer

ios - 如何让 UILabel 显示轮廓文本?

ios - 如何将度数转换为弧度?