简体   繁体   English

每个viewdidload中的代码相同

[英]Same code in every viewdidload

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. 我在每个ViewController中都有相同的代码,它设置ViewControllers视图的背景色,并更改navbaritem的backbutton和titleview。 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. 创建UIViewController的子类,该子类将覆盖执行代码的viewDidLoad方法,然后将需要这种行为的所有其他视图控制器作为其子类。

You have two options. 您有两个选择。

1) Create a common base class that all of your view controller extend from. 1)创建一个通用基类,您所有的视图控制器都将从该基类扩展。 The downside is you probably need two - one for UIViewController and one for UITableViewController . 缺点是您可能需要两个-一个用于UIViewController ,一个用于UITableViewController In these two classes you would put this common code. 在这两个类中,您将放置此通用代码。

2) Create a "helper" class that you call from every viewDidLoad . 2)创建一个“ helper”类,您可以从每个viewDidLoad调用它。 You still need to add a line of code to every viewDidLoad but at least it is only one line. 您仍然需要向每个viewDidLoad添加一行代码,但至少只有一行。 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!) 创建UIViewController的子类以充当您的基本视图控制器(甚至可以将其称为BaseViewController!)

Then, make all of your other view controllers a subclass of this base view controller instead of UIViewController . 然后,使所有其他视图控制器成为此基本视图控制器的子类,而不是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! 由于这些子类将调用[super viewDidLoad] ,因此它们将继承基本视图控制器的viewDidLoad方法中的代码,该方法应包含您的外观代码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM