block和delegate的使用

来源:互联网 发布:新浪微博广告优化师 编辑:程序博客网 时间:2024/04/26 03:59

/**

 *  功能:

 *  1. 分别通过delegateblock方式实现,点击TestTableViewCell上添加的按钮push到一个指定的控制器(TestViewController

 *  2. 当点击cell上的按钮的时候,传一个值(当前cellrow)给ViewController控制器

 *  3. ViewController控制器收到Cell传来的值之后,再返回一个值给TestTabelViewCell,从而达到回调目的

 */


ViewController.m

////  ViewController.m//  MyLayoutSimple////  Created by shlity on 16/5/5.//  Copyright © 2016年 shlity. All rights reserved.//#import "ViewController.h"#import "TestViewController.h"#import "TestTableViewCell.h"@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,CellPushControllerDelegate>@property (nonatomic,retain)UITableView     *tableView;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        self.view.backgroundColor = [UIColor whiteColor];        [self tableView];        // Do any additional setup after loading the view, typically from a nib.}- (UITableView *)tableView{    if (!_tableView) {        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];        _tableView.delegate = self;        _tableView.dataSource = self;        [self.view addSubview:_tableView];    }    return _tableView;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{    return 40;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *identifyCell = @"cell";    TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyCell];    if (!cell) {        cell = [[TestTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell];        cell.delegate = self;    }        [cell startPushViewControllerWithBlock:^NSString *(NSString *strName) {        //TestViewController *testVC = [[TestViewController alloc]init];        //[self.navigationController pushViewController:testVC animated:YES];        NSLog(@"strName:%@",strName);        return [self getCurrentDate];    }];        [cell configureCellWithData:indexPath.row];    return cell;}#pragma mark -- CellPushControllerDelegate- (NSString *)pushViewController:(NSString *)str{    //TestViewController *testVC = [[TestViewController alloc]init];    //[self.navigationController pushViewController:testVC animated:YES];        NSLog(@"str:%@",str);        return [self getCurrentDate];}- (NSString *)getCurrentDate{    NSDate *currentDate = [NSDate date];//获取当前时间,日期    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS"];    NSString *dateString = [dateFormatter stringFromDate:currentDate];    return dateString;}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


TestTableViewCell.h

////  TestTableViewCell.h//  MyLayoutSimple////  Created by shlity on 16/5/6.//  Copyright © 2016年 shlity. All rights reserved.//#import <UIKit/UIKit.h>/** *  功能: *  1. 分别通过delegate和block方式实现,点击TestTableViewCell上添加的按钮push到一个指定的控制器(TestViewController) *  2. 当点击cell上的按钮的时候,传一个值(当前cell的row)给ViewController控制器 *  3. 当ViewController控制器收到Cell传来的值之后,再返回一个值给TestTabelViewCell,从而达到回调目的 *///步骤1 申明一个blocktypedef NSString *(^PushViewController)(NSString *strName);@protocol CellPushControllerDelegate <NSObject>@optional- (NSString *)pushViewController:(NSString *)str;@end@interface TestTableViewCell : UITableViewCell@property (nonatomic,weak)id <CellPushControllerDelegate>delegate;//步骤2 声明一个block属性@property (nonatomic,copy)PushViewController myBlock;- (void)configureCellWithData:(NSInteger )row;//步骤3 将block作为参数作为方法的属性- (void)startPushViewControllerWithBlock:(PushViewController)block;@end


TestTableViewCell.m

////  TestTableViewCell.m//  MyLayoutSimple////  Created by shlity on 16/5/6.//  Copyright © 2016年 shlity. All rights reserved.//#import "TestTableViewCell.h"@implementation TestTableViewCell{    UIButton *button;}- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    if (self) {        button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];        [button setBackgroundColor:[UIColor orangeColor]];        [self.contentView addSubview:button];    }    return self;}- (void)configureCellWithData:(NSInteger )row{    button.tag = row;    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];}// 步骤5 点击按钮时执行block方法- (void)clickAction:(UIButton *)btn{    /**     *  通过delegate方式来回调     */    /*    if (self.delegate && [self.delegate respondsToSelector:@selector(pushViewController:)]) {        NSString *resutl = [self.delegate pushViewController:[NSString stringWithFormat:@"%ld",btn.tag]];        NSLog(@"result:%@",resutl);    }    */        /**     *  通过block方式来回调     */    // 步骤6 点击按钮时执行block方法传给ViewController控制器的值,以及ViewController返回给当前cell中的值    NSString * result = self.myBlock([NSString stringWithFormat:@"%ld",btn.tag]);    NSLog(@"result:%@",result);}// 步骤4 将方法中的block属性赋值给申请的block属性-(void)startPushViewControllerWithBlock:(PushViewController)block{    self.myBlock = block;}- (void)awakeFromNib {    // Initialization code}- (void)setSelected:(BOOL)selected animated:(BOOL)animated {    [super setSelected:selected animated:animated];    // Configure the view for the selected state}@end


block例子2:

//登录的时候,通过block回调验证用户账号和密码是否正确。block用一个BOOL参数类型来判断

#import <Foundation/Foundation.h>typedef void (^RWSignInResponse)(BOOL);@interface RWDummySignInService : NSObject- (void)signInWithUsername:(NSString *)username password:(NSString *)password complete:(RWSignInResponse)completeBlock;@end

#import "RWDummySignInService.h"@implementation RWDummySignInService- (void)signInWithUsername:(NSString *)username password:(NSString *)password complete:(RWSignInResponse)completeBlock {    double delayInSeconds = 2.0;    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){        BOOL success = [username isEqualToString:@"user"] && [password isEqualToString:@"password"];        completeBlock(success); //将这里的消息回调    });}@end


- (IBAction)signInButtonTouched:(id)sender {  // disable all UI controls  self.signInButton.enabled = NO;  self.signInFailureText.hidden = YES;    // sign in//先将账号和密码传到- (void)signInWithUsername:(NSString *)username password:(NSString *)password complete:(RWSignInResponse)completeBlock这个方法中,这个方法收到后,验证验证账号和密码是否正确,然后将结果反馈给自己,达到回到的目的  [self.signInService signInWithUsername:self.usernameTextField.text                            password:self.passwordTextField.text                            complete:^(BOOL success) {                              self.signInButton.enabled = YES;                              self.signInFailureText.hidden = success;                              if (success) {  //收到回调                                [self performSegueWithIdentifier:@"signInSuccess" sender:self];                              }                            }];}


demo下载地址:

http://download.csdn.net/download/mayday550/9514469

1 0