協議和授權機制的實施
假設你有兩個檢視 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 }