IOS-协议和代理

协议和代理
IOS中协议和代理是很常见的,但是肯定有很多人看他感觉挺麻烦的,所以就不想去碰他,不过,你要知道协议和代理会解决一些ios无法解决的问题(论其重要性)。

什么是协议和代理
简单一点来说就是页面之间的传值,当页面A跳转到页面B(可能会附带参数,这不影响),或者是页面B将数据返回给页面A.【代理模式(协议和代理者)是一种设计
模式,原理是通过一个统一的模式,也可以理解为装在一个盒子里面。协议定义一组方法,由某一个类负责实现;代理者作为某个类的一个属性,通常是另一个类的实例
对象、可以负责完成原来那个类不好解决的问题】。代理本身就是一个属性而已,代理的使用往往配合着协议。可能这个类那个类把你们都弄糊涂了,那么我们下面就来看看我们如何去使用他,这也是方便我们去了解这个模式的真正用途。

如何使用代理
在这里必须要提一下,我们在练习的时候怎么去用他都没事,要是在真正项目中,两个页面简单跳转传值也用这个代理,说实话,确实有点过了。在页面B中定义
个协议,声明ー个代理对象。在页面A中,将自己设置为页面B的代理并且完成代理方法。

什么时候使用代理
当一个对象无法直接获取到另一个对象的指针,希望对那个变量进行一些操作,便可使用代理模式。

话不多说,直接看事例:
eg:tableView上Switch,在点击Switch获取Switch的BOOL值。

TableViewCell.h:

#import <UIKit/UIKit.h>

//新建一个协议,协议的名字一般是由“类名+Delegate”
@protocol ViewControllerDelegate <NSObject>

//代理传值方法
-(void)getSwitchIndex:(int)index AndSwitchIsOpen:(BOOL)isOpen;

@end

@interface TableViewCell : UITableViewCell

//委托代理人,代理一般需要使用弱引用(weak)
@property (weak,nonatomic) id<ViewControllerDelegate>delagate;

@property (strong,nonatomic) UIImageView *IconImage;
@property (strong,nonatomic) UILabel *nameLab;
@property (strong,nonatomic) UILabel *newsInfoLab;
@property (strong,nonatomic) UISwitch *switchs;

@property int num;

@end

TableViewCell.m:

#import "TableViewCell.h"
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width

@implementation TableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    UIFont *newFont = [UIFont fontWithName:@"Arial" size:16.0];
    UIFont *newFonts = [UIFont fontWithName:@"Arial" size:14.0];
    
    _IconImage = [[UIImageView alloc]initWithFrame:CGMakeRects(12, 6, 40, 40)];
    _IconImage.layer.masksToBounds = YES;
    _IconImage.layer.cornerRadius = _IconImage.frame.size.height/2;
    [self addSubview:_IconImage];
    
    _nameLab = [[UILabel alloc]initWithFrame:CGMakeRects(65, 5, 100, 20)];
    _nameLab.font = newFont;
    [self addSubview:_nameLab];
    
    _newsInfoLab = [[UILabel alloc]initWithFrame:CGMakeRects(65, 28, 200, 20)];
    _newsInfoLab.font = newFonts;
    _newsInfoLab.textColor = [UIColor grayColor];
    [self addSubview:_newsInfoLab];
    
    _switchs = [[UISwitch alloc]initWithFrame:CGMakeRects(250, 5, 50, 20)];
    [_switchs addTarget:self action:@selector(Get_Switch_Action) forControlEvents:UIControlEventValueChanged];
    [self addSubview:_switchs];
}

-(void)Get_Switch_Action{
    
    //通知执行协议方法
    [self.delagate getSwitchIndex:_num AndSwitchIsOpen:_switchs.on];
}

CG_INLINE CGRect
CGMakeRects(CGFloat x,CGFloat y,CGFloat width,CGFloat height){
    
    CGRect rect;
    
    float w = ScreenWidth/320;
    
    rect = CGRectMake(x * w, y * w, width * w, height * w);
    
    return rect;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

ViewController.m:

#define TABLEVIEW_LENGTH 3
#define TABLEVIEW_NUM 1
#define TABLEVIEW_CELL_HEIGHT 60

#import "ViewControllerC.h"
#import "TableViewCell.h"

@interface ViewControllerC ()<UITableViewDelegate,UITableViewDataSource,ViewControllerDelegate>

@property (strong,nonatomic) UITableView *tableView;

@end

@implementation ViewControllerC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithRed:232/255.0 green:232/255.0 blue:232/255.0 alpha:1.0];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return TABLEVIEW_LENGTH;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return TABLEVIEW_NUM;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return TABLEVIEW_CELL_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *resusedefier = @"CELL";
    UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [tableView registerNib:nib forCellReuseIdentifier:resusedefier];
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:resusedefier];
    if (cell == nil) {
        cell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resusedefier];
    }
    cell.delagate = self;
    cell.IconImage.image = [UIImage imageNamed:@"0"];
    if (indexPath.section == 0) {
        cell.nameLab.text = @"协议代理测试1";
        cell.num = 1;
    }else if (indexPath.section == 1) {
        cell.nameLab.text = @"协议代理测试2";
        cell.num = 2;
    }else if (indexPath.section == 2) {
        cell.nameLab.text = @"协议代理测试3";
        cell.num = 3;
    }
    cell.newsInfoLab.text = @"获取cell上Switch的值";
    return cell;    
}

- (void)getSwitchIndex:(int)index AndSwitchIsOpen:(BOOL)isOpen{
    
    if (index == 1) {
        NSLog(@"Switch1--%@",isOpen?@"YES":@"NO");
    }else if (index == 2){
        NSLog(@"Switch2--%@",isOpen?@"YES":@"NO");
    }else{
        NSLog(@"Switch3--%@",isOpen?@"YES":@"NO");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

看看效果图吧:

打印结果:

以上就是简单自定义协议代理的例子。

                                                        -----辉小鱼

 

posted @ 2016-09-09 13:14  辉小鱼  阅读(345)  评论(5编辑  收藏  举报