I have a view that I want to add some custom drawing to.
I know how to do this with a View that isn't connected to a Nib/Xib file
-drawRect: method.But if I init the view using
[[MyView alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]];
-drawRect: of course doesn't get called. I tried doing the below code in -viewDidLoad
CGRect rect = [[self view] bounds];
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ref, 2.0);
CGContextSetRGBStrokeColor(ref, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBFillColor(ref, 0, 0, 0, 0);
CGContextAddRect(ref, CGRectMake(1, 1, rect.size.width - 10, rect.size.height - 10));
CGContextStrokePath(ref);
CGContextDrawPath(ref, kCGPathFillStroke);
But nothing get drawn. Any ideas?
I think the issue is that you're treating a view and its view controller as interchangeable. For example, there's no -[UIView initWithNibName:bundle:] method — that's a UIViewController method.
Furthermore, a view isn't really like a "canvas" for drawing. A view will be asked to draw itself; in general, it won't be drawn into from "outside."
So:
Rename your subclass of UIViewController from MyView to MyViewController.
Create a new UIView subclass named MyView.
Add a -drawRect: method to your new MyView class that does the drawing you want.
Finally, set the Custom Class of your view controller's view in Interface Builder to MyView using the Identity Inspector.
For example, you should be able to use this for your -[MyView drawRect:] implementation:
- (void)drawRect:(CGRect)rect {
CGRect bounds = [[self view] bounds];
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ref, 2.0);
CGContextSetRGBStrokeColor(ref, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBFillColor(ref, 0, 0, 0, 0);
CGContextAddRect(ref, CGRectMake(1, 1, bounds.size.width - 10, bounds.size.height - 10));
CGContextStrokePath(ref);
CGContextDrawPath(ref, kCGPathFillStroke);
}
The drawing will be clipped to the update rectangle passed in.
Here are three possible solutions, depending on your constraints.
addSubView: method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With