在MVC中,Can View可以与View对话吗?

时间:2013-12-26 12:38:34

标签: ios objective-c model-view-controller

在我的MVC架构中,我需要UIView(testView)作为UIView(mainView)的子视图。这两个视图我都是以编程方式创建的。那么我应该从ViewController创建testView并分配给mainView,或者mainView将直接与testView通信并将其添加为子视图?

2 个答案:

答案 0 :(得分:1)

不,你必须将testView添加为mainView的子视图,而mainView应该是self.view的一部分,如下所示:

[self.view addSubview:mainView];
[mainView addSubview:testView];

答案 1 :(得分:0)

实施例: 这是用UIView类编写的

在.h文件中

 @Property(nonatomic,Strong) UIbutton * backButton;

在.m文件中

@synthesize backButton;
- (id)gettopviewwithBackbutton
  {

UIView *topView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,40)];
topView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"retina_wood_@2X.png"]];
[self addSubview:topView];


backButton =[UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame=CGRectMake(10, 5, 60, 30);
backButton.backgroundColor=[UIColor colorWithRed:.1 green:.5 blue:1 alpha:1.0];
[backButton setTitle:NSLocalizedString(@"back", nil) forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[topView addSubview:backButton];

return self;

}

这是用UIViewController类编写的 TopView是上面代码导入TopView的类名,并编写此代码

TopView *topBar =[[TopView alloc] init];
topBar.frame= CGRectMake(0, yAxis, kWidth, 40);
topBar=[topBar gettopviewwithBackbutton];
[topBar.backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:topBar];
}