Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override the "view" property in UIViewController?

I have a custom UIViewController and custom UIView. I'd like to override the viewcontroller.view property to return MyCustomUIView.

Right now I have:

@interface MyViewController : UIViewController {    
    IBOutlet MyView* view;
}

@property (nonatomic, retain) IBOutlet MyView* view;

This compiles but I get a warning: property 'view' type does not match super class 'UIViewController' property type.

How do I alleviate this warning?

like image 910
Keith Fitzgerald Avatar asked Mar 14 '09 19:03

Keith Fitzgerald


2 Answers

@lpaul7 already posted a link to Travis Jeffery's blog as a comment, but it's so much more correct than all the other answers that it really needs the code to be an answer:

ViewController.h:

@interface ViewController : UIViewController

@property (strong, nonatomic) UIScrollView *view;

@end

ViewController.m:

@implementation ViewController

@dynamic view;

- (void)loadView {
  self.view = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
}

@end

If you using a xib, instead of overriding loadView change the type of your view controller's root view and add IBOutlet to the property.

See Overriding UIViewController's View Property, Done Right for more details.

like image 174
JosephH Avatar answered Sep 29 '22 11:09

JosephH


The short answer is that you don't. The reason is that properties are really just methods, and if you attempt to change the return type, you get this:

  • (UIView *)view;
  • (MyView *)view;

Objective-C does not allow return type covariance.

What you can do is add a new property "myView", and make it simply typecast the "view" property. This will alleviate typecasts throughout your code. Just assign your view subclass to the view property, and everything should work fine.

like image 37
Ecton Avatar answered Sep 29 '22 11:09

Ecton