iOS、swift技术交流!

delegate代理的使用

2016-03-15  本文已影响170人  光明程辉

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

首先:创建一个请求类: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> 代理的用处是什么?

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

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

上一篇 下一篇

猜你喜欢

热点阅读