I have the same code in every ViewController, it sets the backgroundcolor of the ViewControllers' view and it changes the backbutton and the titleview of the navbaritem. Is there a way to avoid this?
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 37, 24)];
[button setImage:[UIImage imageNamed:@"Navbar_BackButton.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(backButtonTabbed:) forControlEvents:UIControlEventTouchDown];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -10)];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
[navbarItem setLeftBarButtonItem:barButton];
[navbarItem setTitleView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Navbar_Title.png"]]];
[[self view] setBackgroundColor:[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Login_Background.png"]]];
It's a perfect case for subclassing.
Create a subclass of UIViewController
which overrides the viewDidLoad
method performing your code, and then make every other view controller that need such behavior a subclass of it.
You have two options.
1) Create a common base class that all of your view controller extend from. The downside is you probably need two - one for UIViewController
and one for UITableViewController
. In these two classes you would put this common code.
2) Create a "helper" class that you call from every viewDidLoad
. You still need to add a line of code to every viewDidLoad
but at least it is only one line. If you need to change the color or whatever, you only change the one class instead of every view controller.
This is a perfect example of the power of inheritance in Object Oriented Programming!
Create a subclass of UIViewController
to act as your base view controller (you could call it BaseViewController, even!)
Then, make all of your other view controllers a subclass of this base view controller instead of UIViewController
. Since these subclasses will call [super viewDidLoad]
, they will inherit the code in the base view controller's viewDidLoad
method, which should contain your appearance code!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.