2

As a newbie in iOS programming, i'm sorry if this question sounds stupid. I draw some rects to mark some text in a UITextView. The only problem is the rects wont scroll with the text. They just stay there. here is the code:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setContentMode:UIViewContentModeRedraw];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 1.0);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGRect rectangle = CGRectMake(0,3.5*self.font.lineHeight,self.frame.size.width,self.font.lineHeight);
    CGContextAddRect(context, rectangle);
    CGContextStrokePath(context);
}

Thanks for your help.

Thank Greg for the answer. I did a bit test and the following codes did the trick. notice that the above codes are in textView.m but the following codes are in ViewController.m:

- (void)viewDidLoad
{
    //other inits....
    [textView setDelegate:self];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [textView setNeedsDisplay];
}
long long
  • 122
  • 8

1 Answers1

1

UITextView is a subclass of UIScrollView. You will have to detect when the scrollview begins scrolling and then update the location of your rectangle dynamically. You can do this by implementing the scrollViewDidScroll: method on your subclass and tracking/updating the location of the rect

Greg Price
  • 2,556
  • 1
  • 24
  • 33