delegate代理的使用

作者: 光明程辉 | 来源:发表于2016-03-15 13:28 被阅读170次

delegate其实是一种思想!它在开发中经常会使用到。例如最常见的tableView就是使用到了代理。

  • 代理最常用的是反向传值!!!通知某个属性发生改变,让代理去实现!

  • 还有就是解耦!!!

  • 下面简单介绍一下使用:

  • 使用代理时,首先要明白它是一种思想!!!

  • 记住使用代理就是 6个步骤就可以了!
    // 第一步,声明协议
    // 第二步,设置代理属性
    // 第二步,通知代理
    // 第4步:遵守协议
    // 第五步:设置成为代理
    // 第六步:实现代理

  • 下面直接用一封装网络的例子来说明:

首先:创建一个请求类:HTTPReqeust
1.当然是:定制协议和协议方法。

  // 1、制定协议
  @protocol HTTPRequestDelegate <NSObject>

  /** 
   WithStatus:下载成功与否
   request:对象本身(把对象传过去,因为对象包含了所有信息)
   */
  - (void)httpRequestLoadingWithStatus:(BOOL)issucceed request:(HTTPReqeust *)request;

  @end

2.设置代理属性(记得weak)
// 2、代理属性
@property (nonatomic,weak) id<HTTPRequestDelegate> delegate;
3.在要实现某个功能时,通知上个界面
// 数据下载完成,通知代理
if ([self.delegate respondsToSelector:@selector(httpRequestLoadingWithStatus:request:)]) {
// 3、通知代理
[self.delegate httpRequestLoadingWithStatus:YES request:self];
}
4.上一个页面ViewController(或另一个页面,遵守协议,并成为HTTPRequest类的代理)
// 4、遵守协议
@interface ViewController () <HTTPRequestDelegate>
5、设置ViewController成为HTTPRequest的代理

  // 调用封装好的类方法
  HTTPReqeust *request = [HTTPReqeust httpReqeustWithStrUrl:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"];
  // 5、设置成为代理
  request.delegate = self;// 此时self和self.delegate 都是ViewController

6.实现代理方法,干你想干的事咯!

  // 6、实现代理方法       
   (void)httpRequestLoadingWithStatus:(BOOL)issucceed request:(HTTPReqeust *)request{
  if (issucceed) {
  //        NSLog(@"%@",request.dataDict);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = request.dataImage;
    [self.view addSubview:imageView];
    }
  }

1.1 设置控件的状态

 启用、禁用
 @property(nonatomic,getter=isEnabled) BOOL enabled;
 选中、不选中
 @property(nonatomic,getter=isSelected) BOOL selected;
 高亮或者不高亮
 @property(nonatomic,getter=isHighlighted) BOOL highlighted;

1.2 设置控件内容的布局

 垂直居中方向
 @property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment;
 水平居中方向
 @property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment;

1.3 添加/删除监听方法

 - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
 - (void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
1> UIButton    -> UIControl -> UIView
2> UILabel     -> UIView
3> UIImageView -> UIView
4> UITextField -> UIControl

* 代理设计模式,在OC中,使用最为广泛的一种设计模式*

1> 代理的用处是什么?

  • 监听那些不能通过addTarget监听的事件!
  • 主要用来负责在两个对象之间,发生某些事件时,来传递消息或者数据

2> 代理的实现步骤
(1) 成为(子)控件的代理,父亲(控制器)成为儿子(文本框)的代理
(2) 遵守协议->利用智能提示,快速编写代码
(3) 实现协议方法

一般情况下,能使用代理的地方都可以使用通知!

相关文章

网友评论

本文标题:delegate代理的使用

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