当 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/