Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing ruled lines on a UITextView for IPhone

I would like to create a view like the notes app on iPhone and therefor need the view to have ruled lines as per the notes app, I have done this in windows where you need to get the font metrics and then draw the lines onto the device context, has anyone done this in the UITextView if so some help would be appriciated

like image 492
Bob Ashmore Avatar asked Dec 10 '22 14:12

Bob Ashmore


1 Answers

Subclass UITextView. Override -drawRect:

- (void)drawRect:(CGRect)rect
{    
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
    CGContextSetLineWidth(context, self.lineWidth);
    CGFloat strokeOffset = (self.lineWidth / 2);

    CGFloat rowHeight = self.font.lineHeight;
    if (rowHeight > 0) {
        CGRect rowRect = CGRectMake(self.contentOffset.x, - self.bounds.size.height, self.contentSize.width, rowHeight);
        while (rowRect.origin.y < (self.bounds.size.height + self.contentSize.height)) {
            CGContextMoveToPoint(context, rowRect.origin.x + strokeOffset, rowRect.origin.y + strokeOffset);
            CGContextAddLineToPoint(context, rowRect.origin.x + rowRect.size.width + strokeOffset, rowRect.origin.y + strokeOffset);
            CGContextDrawPath(context, kCGPathStroke);
            rowRect.origin.y += rowHeight;
        }
    }
}

When you init the text view, be sure to set the contentMode to UIViewContentModeRedraw. Otherwise the lines won't scroll with the text.

self.contentMode = UIViewContentModeRedraw;

This isn't perfect. Ideally you should just draw into the rect that's passed. But I was lazy and this worked for my needs.

like image 174
Dave Batton Avatar answered Dec 21 '22 03:12

Dave Batton