How to handle multiple delegates

☆樱花仙子☆ 提交于 2019-12-21 02:23:47

问题


I've got a view in my app that does pretty much everything, and I like it that way. The problem however is that it's implementing 5 or 6 different delegates, which seems a little bit messy.

My question is, does the view controller have to implement all of the delegates? or is there some way I can separate the code out into different files (without having to do a major restructure or rewrite)?

Here's all the delegates I'm implementing:

@interface MyView : UIViewController <UIScrollViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, MFMailComposeViewControllerDelegate>

回答1:


No problem. The solution is Objective-C categories. You can put this in a separate source file:

#import "MyView.h"
@implementation MyView (UIScrollViewDelegate)
// scroll view delegate method implementations go here
@end

A nice convention is to name this file "MyView+UIScrollViewDelegate.m". The methods you define here will behave just as if they were defined in "MyView.m".

There's no need for the name of the category to match the name of the protocol. You can do this with any set of methods and use any category name you like.



来源:https://stackoverflow.com/questions/2474526/how-to-handle-multiple-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!