- 博主:易飞扬
- 原文链接 : http://www.yifeiyang.net/iphone-developer-advanced-5-programming-custom-uiviewcontroller/
- 转载请保留上面文字。
iPhone开发进阶(5) --- 编程定制UIViewController
如第三讲中看到的,即使不使用 XIB 文件,也可以通过重写 viewDidLoad 函数来配置任意的view或者是Controller。这里我们看看怎样编程定制这样的view和Controller。
首先如果 UIViewController 的 init 方法找不到 XIB 文件的话,会自动创建一个自己的 UView 对象,使用 viewDidLoad 将自己登录。所以,我们可以在定制 UIViewController 时实现 viewDidLoad 方法、将 view 作为 subview。
例子中 view 的背景为蓝色,在其上设置一个 UIButton。
第一步,在 CustomViewControllerAppDelegate.m 文件中定义 CustomViewController 类。
1 2 3
@interface CustomViewController : UIViewController { } @end
同时,在 CustomViewControllerAppDelegate.h 文件中实现该实例。
1 2 3 4 5 6
@class CustomViewController; @interface CustomViewControllerAppDelegate : NSObject { UIWindow *window; CustomViewController* controller; }
@class CustomViewController 类似与C++中的类先声明。 因为不需要外部对象的访问,所以没有 @property 宣言。
CustomViewController 的实例在 CustomViewControllerAppDelegate 类的成员函数 applicationDidFinishLaunching 中生成,然后用 addSubview 将 CustomViewController实例中的 view 添加进去。最后在 CustomViewControllerAppDelegate 释放的时候(dealloc)中释放其实例。代码如下所示:
1 2 3 4 5 6 7 8 9 10 11
- (void)applicationDidFinishLaunching:(UIApplication *)application { viewController = [[CustomViewController alloc]init]; [window addSubview:viewController.view]; [window makeKeyAndVisible]; } - (void)dealloc { [window release]; [controller release]; [super dealloc]; }
用 window addSubview 表示最初的view。
然后像下面简单地声明和实现 CustomViewController。在 CustomViewController 的 viewDidLoad 函数中设置背景色为蓝色。
1 2 3 4 5 6 7 8 9 10
@interface CustomViewController : UIViewController { } @end @implementation CustomViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blueColor]; } @end
编译以后执行一下,看到下面的结果。
接下来我们再来添加按钮,我们动态生成一个 UIButtonTypeInfoLight 类型的按钮,设置了按钮的 frame 后,用addSubview 添加到 view 上。
1 2 3 4 5 6 7 8 9
@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
最终的效果如下:
下一讲我们来具体定制按钮动作。