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
UIViewControllerwhich overrides theviewDidLoadmethod performing your code, and then make every other view controller that need such behavior a subclass of it.