? ? ? ? swift協(xié)議代理的使用跟oc的協(xié)議代理差不套多扛邑,不過語法上還是有不小的區(qū)別。swift使用協(xié)議的關(guān)鍵字:protocol,協(xié)議的語法:protocol Pro1{//這里定義屬性或者方法}闷煤,
? ? ? ? swift創(chuàng)建協(xié)議并聲明代理屬性:
? ? ? ? protocol ? ?ViewControllerSDelegate {
? ? ? ? ? ? ? ? ? ? funcViewControllerDelegateLoadDataOne(); ? // 不帶參的
? ? ? ? ? ? ? ? ? ? funcViewControllerDelegateLoadDataTwo(str:String); // 帶參的
? ? ? ? }
? ? ? ?func doClick() { ?// 點擊觸發(fā)的方法
? ? ? ? ? ? ? ? ? self.delegate?.funcViewControllerDelegateLoadDataOne()//讓代理去執(zhí)行代理方法
? ? ? }
? ? ? ? 控制器方法實現(xiàn)
? ? ? ? class ?ViewController:UIViewController,ViewControllerDelegate {
? ? ? ? ? ? ? var ? delegate:ViewControllerDelegate?;
? ? ? ? ? ? ? override ? func ? viewDidLoad() {
? ? ? ? ? ? ? ? ? ? ? ?super.viewDidLoad()
? ? ? ? ? ? ? ? ? ? ? ?self.delegate=self;
? ? ? ? ? ? ? }
? ? ? ? ? ? ? internal ?func ?ViewControllerDelegateLoadDataOne() {
? ? ? ? ? ? ? }
? ? ? ? ? ? ? func ? ViewControllerDelegateLoadDataTwo(str:String) {
? ? ? ? ? ? ?}
? ? ? ?}
? ? ? oc擬定協(xié)議:
? ? ? ? ? ? @protocol? ViewControllerDelegate ?<NSObject>
? ? ? ? ? ? @required//缺省屬性,必須要實現(xiàn)
? ? ? ? ? ? - (void)show;//show是必須要實現(xiàn)
? ? ? ? ? ? ?@optional//可選實現(xiàn)
? ? ? ? ? ? ?- (void)show1;//show1是可實現(xiàn)也可不實現(xiàn)
? ? ? ? ? ? @end
? ? ? ? ? ?- (void) onClick {?
? ? ? ? ? ? ? ? ? ? if([self.delegate respondsToSelector:@selector(show)]) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [self.delegate show];
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? }
? ? ? ? ? ? 遵守協(xié)議
? ? ? ? ? @interface? ViewController()<ViewControllerDelegate>
? ? ? ? ? ?@end
? ? ? ? ? ?設(shè)置代理實現(xiàn)方法 ??
? ? ? ? ? ? - (void)viewDidLoad {
? ? ? ? ? ? ? ? ? ? ?[superviewDidLoad];
? ? ? ? ? ? ? ? ? ? ?self.delegate = self; // 設(shè)置代理
? ? ? ? ? ? ?}
? ? ? ? ? ? ?-(void) show {
? ? ? ? ? ? }
? ? ? ? ? ? -(void) show1{
? ? ? ? ? ? }