Subclass a Delegate?

2019-07-17 17:34发布

I have a class called ToolbarView which is a subclass of UIView and basically creates a UIView that has a disappearing / reappearing UIToolbar on top. I also have a subclass of ToolbarView called DraggableToolbarView which enables the user to drag the view around the screen.

I need to create a delegate for ToolbarView so it can notify another object / class of when the toolbar reappears and disappears. I also need to create a delegate for DraggableToolbarView so I can notify another object / class when the view is dragged.

Currently, I have create a separate delegate for each, but I am wondering if there is a better pattern for this? Maybe implement one delegate for ToolbarView, and list the delegate methods from DraggableToolbarView as optional? Or is there a way to subclass a delegate?

What is the best / cleanest way to accomplish this?

3条回答
疯言疯语
2楼-- · 2019-07-17 17:39

If you create a protocol for your delegate methods (always a good idea anyway), you can have another protocol adopt the first. That sets up an inheritance-like relationship:

@protocol ToolbarViewDelegate
// some methods
@end

@protocol DraggableToolbarViewDelegate <ToolBarViewDelegate>
// additional methods
@end
查看更多
做自己的国王
3楼-- · 2019-07-17 18:01

Yes, you can have inheriting protocols:

@protocol Proto1 

@reqired
-(void) somethingHappened:(id) sender;

@optional
-(void) somethingElseHappened:(id) sender;

@end

@protocol Proto2<Proto1>

// this now contains all of the method signatures found in proto1, with the addition of new ones!

-(void) somethingSpecialHappened:(id) sender;

@end
查看更多
【Aperson】
4楼-- · 2019-07-17 18:03

I think you're doing it right.

Consider UITextView which is a subclass of UIScrollView. Each has its own delegate protocol that's responsible for reacting to a specific set of messages. As long as you think of visibility and dragging as separate concerns, allowing different objects to handle their delegation seems logical.

查看更多
登录 后发表回答