中心NSTextAttachment图像旁边的单行UILabel

中心NSTextAttachment图像旁边的单行UILabel

本文介绍了中心NSTextAttachment图像旁边的单行UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to append an NSTextAttachment image to my attributed string and have it centered vertically.

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

I've used the following code to create my string

        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的顶部对齐。

However, the image appears to align to the top of the cell's textLabel.

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

How can I change the rect in which the attachment is drawn?

推荐答案

您可以通过子类化来更改矩形 NSTextAttachment 并覆盖 attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:。示例:

You can change the rect by subclassing NSTextAttachment and overriding attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:. Example:

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {
    CGRect bounds;
    bounds.origin = CGPointMake(0, -5);
    bounds.size = self.image.size;
    return bounds;
}

这不是一个完美的解决方案。您必须通过眼睛找出Y原点,如果您更改字体或图标大小,您可能想要更改Y原点。但我无法找到更好的方法,除非将图标放在单独的图像视图中(这有其自身的缺点)。

It's not a perfect solution. You have to figure out the Y-origin "by eye" and if you change the font or the icon size, you'll probably want to change the Y-origin. But I couldn't find a better way, except by putting the icon in a separate image view (which has its own disadvantages).

这篇关于中心NSTextAttachment图像旁边的单行UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:19