1

我是 iOS 开发的新手。为了让我的 iOS 应用程序很好地划分,我想以编程方式创建 UIView 和 UIViewController,并在创建后将它们绑定在一起。

所以,我做了以下事情:在我的视图控制器中,我有这个:

-(void)loadView {    
   NSLog(@"HPSMainMenuViewController loadView starting"); 
   HPSMainMenuView* mainmenuView = [[HPSMainMenuView alloc]initWithFrame:CGRectZero];
   self.view = mainmenuView; 
}

在我看来,我有这个:

-(id)initWithFrame:(CGRect)frame {
   self = [super initWithFrame:frame];
   if (self) {
      // Initialization code
      NSLog(@"HPSMainMenuView initWithFrame starting");
      [self setup];
   }
   return self; 
}
-(void)setup {

     UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     btn.tag = E_PROFILE_BUTTON;
     [btn setTitle:@"Option1" forState:UIControlStateNormal];

     [self.view addSubview:btn ];

     btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     btn.tag = E_CONTACTS_BUTTON;
     [btn setTitle:@"Option2" forState:UIControlStateNormal];

     [self.view addSubview:btn ];

     self.title = @"Hello"; 
}

这是正确的方法吗(假设我想要完全的程序控制)。在 ViewController 中动态构建视图似乎是错误的,因此我的方法是在实际UIView类中构建视图。

最后,我正在使用 loadView;我应该使用viewDidLoad吗?如果是这样,为什么?

非常感谢。

4

1 回答 1

2

What you are doing is correct, and actually good. Many developers keep their view controllers and views heavily tied together but if you want to keep them separate then that's great.

loadView is where you should be creating and initializing everything. viewDidLoad can be called multiple times if the view is unloaded/reloaded due to memory warnings (for example). So viewDidLoad is where you would restore saved state, make your view correctly reflect your model, or any other initialization that you can't do in loadView.

于 2012-05-30T11:04:17.467 回答