I assume that you expected something more fundamental, and then just passed the action of the button to the controller. I always follow the MVC pattern when the model / view / controller works together. It solves your problem and many others. And I want to share my experience.
- A separate controller from the view and model: do not put all the "business logic" in the classes associated with the view; this makes the code very unusable. Create controller classes to host this code, but make sure the controller classes do not make too many assumptions about the presentation.
- Define a callback API using
@protocol using @optional , if not all methods are necessary. - For a view, define a protocol, for example,
<view class name>Protocol (NewsViewProtocol example). For the controller, define the delegate as <view class name>Delegate (example NewsViewDelegate) and dataSource, for example <view class name>DataSource (example NewsViewDataSource). Store all these @protocols in a single file named <view class name>Protocol.h (NewsViewProtocol.h example)
A brief example:
NewsView.h Content
// // NewsView.h @interface NewsView : UIView <NewsViewProtocol> { @protected NSObject* delegate_; NSObject* dataSource_; } @end
Content of NewsController.h and .m
// // NewsController.h @interface NewsController : UIViewController <NewsViewDataSource, NewsViewDelegate> { } @property (nonatomic, weak) UIView<NewsViewProtocol>* customView; @end @implementation NewsController - (void)viewDidLoad { [super viewDidLoad]; self.customView = (UIView<NewsViewProtocol>*)self.view; [self.customView setDelegate:self]; [self.customView setDataSource:self]; } @end
Content NewsViewProtocol.h
// // NewsViewProtocol.h @protocol NewsViewProtocol; @protocol NewsViewDelegate<NSObject> @optional - (void)someAction; - (void)newsView:(UIView<NewsViewProtocol>*)newsView didSelectItemAtIndexPath:(NSIndexPath *)indexPath; @end @protocol NewsViewDataSource<NSObject> @required - (id)newsView:(UIView<NewsViewProtocol>*)newsView itemAtIndexPath:(NSIndexPath *)indexPath; - (NSInteger)numberOfItemsInNewsView:(UIView<NewsViewProtocol>*)newsView section:(NSInteger)section; - (BOOL)newsView:(UIView<NewsViewProtocol>*)newsView shouldDisplaySection:(NSInteger)section; @end @protocol NewsViewProtocol<NSObject> @required //Never retain delegate instance into implementation of this method - (void)setDelegate:(NSObject<NewsViewDelegate>*)delegate; //Never retain delegate instance into implementation of this method - (void)setDataSource:(NSObject<NewsViewDataSource>*)dataSource; - (void)reload; @end
You can assume that it is redundant. In a simple view controller, YES. But if you are developing a very complex screen with a huge amount of data, then it gives you some advantages:
- Helps you share responsibility between a view and a controller.
- Saves your code.
- Makes the code more reusable.
source share