【问题标题】:In MVC, Can View talk to View?在 MVC 中,View 可以与 View 对话吗?
【发布时间】:2014-01-14 02:52:44
【问题描述】:

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

【问题讨论】:

  • 嗨,看看我写的答案,我举了一个例子,希望对你有帮助
  • 视图从不互相交谈,因为他们不知道世界是存在的,所以你必须简要清楚你想要实现什么,这样我们才能理解模式
  • 这取决于测试视图的复杂程度。如果测试视图非常简单,那么我认为应该是从视图控制器创建的方法,否则您可以为测试视图编写一个类。创建它的实例并将其添加到主视图。
  • 让我说清楚,我的 testView 和 mainView 是两个独立的类(UIView 的子类),我想问我应该在 mainView 还是 viewController 中创建 testView 的实例?
  • 在主视图中添加测试视图

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


【解决方案1】:

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

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

【讨论】:

  • 我的 mainView 是 UIView 的独立子类,而 testView 也是 UIView 的独立子类。我在问 mainView 可以与 testView 通信还是 viewController 必须创建 testView 并将其传递给 mainView?
  • 你需要在testViewController中创建mainView的对象,然后在创建的对象中添加textView的子视图
【解决方案2】:

示例: 这是写在 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 是上面代码的类名 import 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];
}

【讨论】:

    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2013-01-17
    相关资源
    最近更新 更多