Simple UIView drawRect not called

I canโ€™t understand what the problem is. I have a very simple UIViewController with a very simple viewDidLoad method:

-(void)viewDidLoad { NSLog(@"making game view"); GameView *v = [[GameView alloc] initWithFrame:CGRectMake(0,0,320,460)]; [self.view addSubview:v]; [super viewDidLoad]; } 

And my GameView is initialized as follows:

 @interface GameView : UIView { 

and it just has a new drawRect method:

 - (void)drawRect:(CGRect)rect { [super drawRect:rect]; NSLog(@"drawing"); } 

In my console, I see โ€œcreating a game view,โ€ but the โ€œdrawingโ€ is never printed. What for? Why is my drawRect method not called in my custom UIView. I'm literally just trying to draw a circle on the screen.

+6
source share
4 answers

Have you tried to specify a frame in view initialization? Since you are creating a custom UIView, you need to specify a frame to represent before invoking the drawing method.

Try changing viewDidLoad to the following:

 NSLog(@"making game view"); GameView *v = [[GameView alloc] initWithFrame:CGRectMake(0,0,320,460)]; if (v == nil) NSLog(@"was not allocated and/or initialized"); [self.view addSubview:v]; if (v.superview == nil) NSLog(@"was not added to view"); [super viewDidLoad]; 

let me know what you get.

+12
source

Check if your view is displayed. If the view is not currently displayed, drawRect will not be called even if you add the view to its supervisor. It is possible that your opinion is blocked by some other kind.

And as far as I know, you do not need to write [super drawRect] ;

Note that even if viewDidLoad is called on the view controller, this does not necessarily indicate that the view controller view is displayed on the screen. Example. Suppose a controller of type A has ivar where a view controller B is stored, and a view of the controller is currently displayed. Also suppose that B is highlighted and introduced. Now, if any method in B causes the B-image to be accessible by viewDidLoad in B, it will be called as a result, regardless of whether it is displayed.

0
source

If you are using a lib or CocoaTouch file, you may need to override the initWithCoder method instead of viewDidLoad.

Objective-C:

 - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { //Do Stuff Here } return self; } 
0
source

I had an idea of โ€‹โ€‹what was off the screen that I would load onto the screen and then redraw. However, when clearing the auto-layout constraints in Xcode, he decided that my appearance should have a frame (0,0,0,0) (x, y, w, h). And with a size of (0,0), the view will never load.

Make sure the NSView has a non-zero frame size, otherwise drawRect will not be called.

0
source

All Articles