iOS中的NSAttributedString中NSBackgroundColorAttributeName-like属性?

我正在计划使用NSAttributedString来突出部分string与用户search的匹配查询。 但是,我找不到一个iOS的等价物NSBackgroundColorAttributeName – 没有kCTBackgroundColorAttributeName 。 这样的事情是否存在,类似于NSForegroundColorAttributeName成为kCTForegroundColorAttributeName的方式?

不,核心文本中不存在这样的属性,您必须在文本下方绘制自己的矩形来模拟它。

基本上,你必须找出填充string中给定范围的矩形。 如果使用生成CTFramesetter布局,则需要使用CTFrameGetLinesCTFrameGetLineOrigins获取其行和源。

然后遍历这些行并使用CTLineGetStringRange来找出哪些行是你想要突出显示的范围的一部分。 要获得矩形填充,请使用CTLineGetTypographicBounds (对于高度)和CTLineGetOffsetForStringIndex (对于水平偏移和宽度)。

NSBackgroundColorAttributeName在iOS 6中可用,您可以通过以下方式使用它:

 [_attributedText addAttribute: NSBackgroundColorAttributeName value:[UIColor yellowColor] range:textRange]; [_attributedText drawInRect:rect]; 

drawInRect:将支持iOS 6支持的NSBackgroundColorAttributeName和所有的NS * AttributeNames。

对于CTFrameDraw(),不支持背景文本的颜色。

码:

 - (void)drawRect:(CGRect)rect { // First draw selection / marked text, then draw text CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); CGContextSetTextMatrix(context, CGAffineTransformIdentity); CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1.0, -1.0); [_attributedText drawInRect:rect]; CGContextRestoreGState(context); // CTFrameDraw(_frame, UIGraphicsGetCurrentContext()); }