美文网首页
iOS学习笔记:添加delegate

iOS学习笔记:添加delegate

作者: 木登与木由 | 来源:发表于2018-07-10 16:48 被阅读43次

1、委托者添加代理.

@protocol  MyUIViewDelegate <NSObject>
- (void)funcWithIndex:(int)index;
@end

2、委托者申明一个属性:委托者里得有一个属性代表被委托者, 注意这个属性是弱引用.

@interface  MyUIView: UIView
@property(nonatomic, weak) id<MyUIViewDelegate> delegate;

3、被委托者声明实现了协议:被委托者需要声明自己实现了委托者的协议.

@interface MyUIViewController : UIViewController <MyUIViewDelegate>
@end

4、将被委托者赋给委托者的代理

MyUIView *view = [[MyUIView alloc]init];
view.delegate = self;

5、被委托者实现代理方法

- (void)funcWithIndex:(int)index{
// 走完第六步后,这里将得到返回的值  即:index=5
}

6、委托者.m文件里,在需要的时候,使用被委托者调用代理方法

if(self.delegate && [self.delegate respondsToSelector:@selector(funcWithIndex:)]){
   [self.delegate  funcWithIndex:5];
}

相关文章

网友评论

      本文标题:iOS学习笔记:添加delegate

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