美文网首页
iOS_简述delegate

iOS_简述delegate

作者: 古流风 | 来源:发表于2016-06-28 10:25 被阅读418次

    简单整理一下delegate

    delegate分为主动方和被动方,也可以说是委托方和被委托方。
    主动方:
    1、生成协议
    2、要有个遵守协议的属性
    3、让代理去调用协议中的方法

    被动方:
    1、遵守协议
    2、设置代理
    3、实现协议方法

    现在说下主动方,上代码
    <pre><code>
    secondVC.h:

    //生成协议

    @protocol SecondViewControllerDelegate<NSObject>

    -(void)setBackgroundColor:(UIColor *)color;

    @end

    @interface SecondViewController : UIViewController

    //2、遵守协议的属性

    @property (nonatomic,assign)id< SecondViewControllerDelegate >delegate;

    @end

    secondVC.m

    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    if (self.delegate && [self.delegate respondsToSelector:@selector(setViewBackgroundColor:)]) {

    [self.delegate setViewBackgroundColor:[UIColor redColor]];//3、代理调用协议中的方法

    }else{

    NSLog(@"没有设置道理过实现协议中的方法");

    }

    [self.navigationController popViewControllerAnimated:YES];

    }
    </code></pre> 被动方:<pre><code>
    //被动方的代码都在.m中

    1、遵守协议:

    @interface ViewController ()< SecondViewControllerDelegate >

    @end

    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    SecondViewController * vc = [[SecondViewController alloc]init];

    vc.delegate = self;//设置代理

    [self.navigationController pushViewController:vc animated:YES];

    }

    //实现协议方法

    -(void)setViewBackgroundColor:(UIColor *)color{

    self.view.backgroundColor = color;

    }
    </code></pre>一个简单的代理就这点东西,至于怎么用就看你理解了。

    相关文章

      网友评论

          本文标题:iOS_简述delegate

          本文链接:https://www.haomeiwen.com/subject/bqktjttx.html