Question

I’m a new developer on iOS and I’m struggling with the DrawRect method: the first time it gets called, it actually draws what I want where I want, but all the next calls to DrawRect fail to move my view (although they do resize it).
I therefore made a minimalist test app to reproduce my problem but still could not isolate the cause.
This app just draws a blue rectangle in the top left corner, and each time you tap into it, it’s supposed to:

  • Switch width and height (this does work)
  • Move the rectangle by 10 points to the right (this does not work)

Of course I checked that DrawRect actually gets called and that its bounds did change to what I wanted, but still, my view does not want to move.

==============================================
Here’s my ViewController (RVTViewController.m)
==============================================

@implementation RVTViewController
(void)viewDidLoad`
{
    [super viewDidLoad];
    if (!self.myView)
    {
        CGRect viewBounds = CGRectMake(0,0,100,150);
        self.myView = [[RVTView alloc] initWithFrame:viewBounds];
        [self.view addSubview:self.myView];        
        UITapGestureRecognizer* gestRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self.myView addGestureRecognizer:gestRec];
    }
}

-(void) tap:(UITapGestureRecognizer*) gesture
{
    CGRect newViewBounds = CGRectMake(self.myView.bounds.origin.x + 10,
                                      self.myView.bounds.origin.y,
                                      self.myView.bounds.size.height,
                                      self.myView.bounds.size.width);
    self.myView.bounds = newViewBounds;
    [self.myView setNeedsLayout]; 
    [self.myView setNeedsDisplay];
}
@end

=====================================
And here’s my custom view (RVTView.m)
=====================================

@implementation RVTView
- (void)drawRect:(CGRect)rect
{
    CGRect newBounds = self.bounds;
    UIBezierPath* newRect = [UIBezierPath bezierPathWithRect:newBounds];
    [[UIColor blueColor] setFill];
    UIRectFill(self.bounds);
    [newRect stroke];
}
@end

Can someone please tell me what I am getting wrong ?

Was it helpful?

Solution

Using [self.myView setFrame:newViewBounds]; instead of self.myView.bounds = newViewBounds; fixed the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top