协议和授权机制的实施
假设你有两个视图 ViewA 和 ViewB
ViewB 的实例是在 ViewA 内创建的,所以 ViewA 可以向 ViewB's 实例发送消息,但是为了反过来我们需要实现委托(这样使用委托 ViewB's 实例就可以向 ViewA 发送消息)
请按照以下步骤实施委派
-
在
ViewB中创建协议@protocol ViewBDelegate -(void) exampleDelegateMethod; @end -
在 sender 类中声明委托
@interface ViewB : UIView @property (nonatomic, weak) id< ViewBDelegate > delegate; @end -
采用 Class ViewA 中的协议
@interfac ViewA: UIView < ViewBDelegate > -
设置代理
-(void) anyFunction { // create Class ViewB's instance and set the delegate [viewB setDelegate:self]; } -
在类
ViewA中实现委托方法-(void) exampleDelegateMethod { // will be called by Class ViewB's instance } -
使用
ViewB类中的方法将委托方法调用为-(void) callDelegateMethod { [delegate exampleDelegateMethod]; //assuming the delegate is assigned otherwise error }