Reprinted text.IPhone development (5) --- programming custom uiviewcontroller
As shown in the third lecture, even if the XIB file is not used, you can rewrite the viewdidload function to configure any view or controller. Here we will look at how to program and customize such views and controllers.
First, if the XIB file cannot be found in the init method of uiviewcontroller, A uview object is automatically created and you can use viewdidload to log on to the system. Therefore, we can implement the viewdidload method when customizing the uiviewcontroller and use the view as the subview.
In this example, the background of the view is blue and a uibutton is set on it.
Step 1: Define the customviewcontroller class in the customviewcontrollerappdelegate. M file.
@ Interface customviewcontroller: uiviewcontroller {
}
@ EndAt the same time, this instance is implemented in the customviewcontrollerappdelegate. h file.
@ Class customviewcontroller;@ Interface customviewcontrollerappdelegate: nsobject {
Uiwindow * window;
Customviewcontroller * controller;
}
@ Class customviewcontroller is similar to class declaration in C ++. Because access to external objects is not required, there is no @ property declaration.
The mviewcontroller instance is generated in the member function applicationdidfinishlaunching of the customviewcontrollerappdelegate class, and then added the view in the customviewcontroller instance with addsubview. Finally, when customviewcontrollerappdelegate is released (dealloc), its instance is released. The Code is as follows:
-(Void) applicationdidfinishlaunching uiapplication *) Application {
Viewcontroller = [[customviewcontroller alloc] init];
[Window addsubview: viewcontroller. View];
[Window makekeyandvisible];
}-(Void) dealloc {
[Window release];
[Controller release];
[Super dealloc];
}
Use Window addsubview to represent the original view.
Then, declare and implement customviewcontroller in the following simple way. In the viewdidload function of customviewcontroller, set the background color to blue.
@ Interface customviewcontroller: uiviewcontroller {
}
@ End@ Implementation customviewcontroller
-(Void) viewdidload {
[Super viewdidload];
Self. View. backgroundcolor = [uicolor bluecolor];
}
@ End
Compile and execute the command. The following result is displayed.
Next we will add a button. We will dynamically generate a uibuttontypeinfolight button. After setting the frame of the button, we will add it to the view with addsubview.
123456789 |
@implementation CustomViewController- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blueColor]; UIButton* button = [UIButton buttonWithType:UIButtonTypeInfoLight]; button.frame = CGRectMake(100,100,100,100); [self.view addSubview:button];}@end |
The final effect is as follows:
Next let's talk about the specific button actions.