How to handle multiple delegates

2019-03-20 02:32发布

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条回答
干净又极端
2楼-- · 2019-03-20 03:32

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.

查看更多
登录 后发表回答