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

在这里输入图像描述

我怎样才能改变绘制附件的矩形?


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

- (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原点。 但我找不到更好的方法,除了将图标放在单独的图像视图中(这有其自身的缺点)。


试试- [NSTextAttachment bounds] 。 不需要子类。

对于上下文,我渲染一个UILabel作为附件图像,然后像下面这样设置边界: attachment.bounds = CGRectMake(0, self.font.descender, attachment.image.size.width, attachment.image.size.height)以及标签图像中文本的基线和属性字符串中的文本根据需要排列。


我找到了一个完美的解决方案,虽然对我来说就像是一种魅力,但是你必须自己尝试一下(可能常常取决于设备的分辨率以及其他方面;)

func textAttachment(fontSize: CGFloat) -> NSTextAttachment {
    let font = UIFont.systemFontOfSize(fontSize) //set accordingly to your font, you might pass it in the function
    let textAttachment = NSTextAttachment()
    let image = //some image
    textAttachment.image = image
    let mid = font.descender + font.capHeight
    textAttachment.bounds = CGRectIntegral(CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height))
    return textAttachment
}

应该工作,不应该以任何方式模糊(感谢CGRectIntegral

链接地址: http://www.djcxy.com/p/28297.html

上一篇: Center NSTextAttachment image next to single line UILabel

下一篇: Keep UIImageView and UILabel center aligned