如何使UITextView背景线与文本对齐?

时间:2013-08-06 05:06:06

标签: ios uitextview

我正在尝试绘制UITextView的背景线, 这是我用来绘制那些线的代码

    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, self.horizontalLineColor.CGColor);
    CGContextSetLineWidth(context, kDashedBorderWidth);
    CGContextSetLineDash(context, 0, kDashedLinesLength, kDashedCount) ;

    CGFloat baseOffset = 9.0f + self.font.descender;
    CGFloat boundsX = self.bounds.origin.x;
    CGFloat boundsWidth = self.bounds.size.width;

    NSInteger firstVisibleLine = MAX(1, (self.contentOffset.y / self.font.lineHeight));
    NSInteger lastVisibleLine = ceilf((self.contentOffset.y + self.bounds.size.height) / self.font.lineHeight);
    for (NSInteger line = firstVisibleLine; line <= lastVisibleLine; ++line)
    {
        CGFloat linePointY = (baseOffset + (self.font.lineHeight * (float)line));            
        CGContextMoveToPoint(context, boundsX, linePointY);
        CGContextAddLineToPoint(context, boundsWidth, linePointY);
    }
    CGContextClosePath(context);
    CGContextStrokePath(context);

结果如图所示 enter image description here

它似乎正确地获得第一行,但以下行未与文本对齐。

我可能错过了什么?是否与本地化设置有关?

3 个答案:

答案 0 :(得分:4)

您可能需要检查this

答案 1 :(得分:2)

经过几次实验后,我发现lineHeight实际上比实际高度略小,约为1磅。

这是工作版

CGFloat baseOffset = 7.0f + self.font.descender;

// ....

for (NSInteger line = firstVisibleLine; line <= lastVisibleLine; ++line)
{
    CGFloat linePointY = (baseOffset + ((self.font.lineHeight + 1.0f) * (float)line));            
    CGContextMoveToPoint(context, boundsX, linePointY);
    CGContextAddLineToPoint(context, boundsWidth, linePointY);
}

如果您实施自己的版本,我认为您需要了解两个神奇数字:7.0f1.0f

这只是一个解决方法,我很想知道更好的方法来实现这一目标。

答案 2 :(得分:1)

这不是确切的解决方案,而是这个UI的方法。该UI给出了带下划线的文本的感觉。

但我想使用它,我们可以实现您所需的相同功能。

希望这有帮助。