具有自定义 View 的 iOS MVC 实现

标签 ios model-view-controller custom-view

当 View 很简单时,它们的 IBAction 和 IBoutlet 位于 View Controller 中, View Controller 分配要加载的相应模型,并在模型准备好时通知 View Controller 。

由于我的项目包含每个 View Controller 的许多自定义 View ,我想在自定义 View 本身中实现操作并从 Controller (ViewController) 设置数据。 我应该能够为 iPhone 和 iPad 使用相同的 Controller 和模型,只是 UI 发生了变化。

我担心如何在模型更改时将数据从 View 传递到 View Controller 并在 View 上显示数据?

谁能建议我在 View 之间传递数据<---> viewcontroller (controller) <---> model?

最佳答案

为此,我使用委托(delegate)设计模式。它看起来像这样:

MyView.h

@protocol MyViewDelegate <NSObject>
- (void)customViewDidSomething;
@end

@interface MyView : UIView

@property (nonatomic, assign) id<MyViewDelegate> delegate

@end

MyView.m

- (void)userDidSomething {
   [_delegate customViewDidSomething];
}

MyViewController.h

#import "MyView.h"

// ViewController has to implement the protocol
@interface MyViewController <MyViewDelegate>

@property (nonatomic, retain) IBOutlet MyView myView;

MyViewController.m

- (void)viewDidLoad { // Set the delegate somewhere
   _myView.delegate = self
}

- (void)customViewDidSomething {
   // Ok VC is aware that something happened
   // Do something (tell subview to do something ?)
}

关于具有自定义 View 的 iOS MVC 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799302/

相关文章:

scrollview - Sproutcore:在SC.ScrollView中将自定义 View 用作contentView

ios - 为什么打印语句没有按正确的顺序执行??我疯了还是Xcode?

android - Cordova FCM - 构建错误 : Failed to apply plugin [id 'com.google.gms.google-services' ]

objective-c - 我在此Objective-C方法中发生内存泄漏,有人可以告诉我在哪里吗?

asp.net-mvc-3 - MVC 3 - route 的斜线和空格

ios - 将自定义 UIView 更改为 UIScrollView

ios - 如何在 Storyboard中正确创建叠加 View ?

c++ - 在 C++ 桌面应用程序的上下文中使用 MVC 的导航/ View 流

php - 我怎样才能扩展 Zend_Controller_Action 使一个函数在所有 Controller 中通用

android - Twitter 客户端中的自动链接@提及