iOS初级开发笔记:Block回调,实现简单的绑定支付宝逻辑

1,079 阅读2分钟

绑定支付宝首页和填写资料绑定页之间,

需要在填写页填写好手机号,验证码等,点击确认绑定后跳回到绑定首页。并且绑定按钮变为已绑定按钮暂未绑定label变为输入的支付宝账号。并且点击已绑定按钮会跳转到解绑界面。

整个流程在app上展示为

一、在传信息的controller内(即填写页的controller内)创建Block:

fillAlipayViewController.h中:

// 创建block
typedef void(^bindAlipayBlock)(NSDictionary *bindDict);

// 监听返回的绑定状态
@property (nonatomic, copy) bindAlipayBlock returnBlock;
  • 这里解释一下创建语句:

    • 我们可以通过关键字typedef来为block起类型名称,然后直接通过类型名进行block的创建;
    • void为返回值;
    • ^bindAlipayBlock为block名称;
    • NSDictionary *bindDict为参数。
  • 因为需要传两个值(支付宝号和绑定状态),所以创建类型是字典,命名也要明确Block是什么类型:

(NSDictionary *bindDict)

fillAlipayViewController.m中:

需创建全局变量:_alipayAccount即为监听输入的支付宝账号全局变量。支付宝账号为字符串:

{
    NSString *_alipayAccount;//支付宝账号
}

在输入完成后点击确认的点击事件中,确定若响应Block实例,则传出字典,字典内写相应的键值,(即将绑定YES状态和支付宝账号传出去):

if (self.returnBlock){

self.returnBlock(@{@"isBind":@"YES",@"alipayAccount":self->_alipayAccount});
}

接着下面是返回上一页绑定首页语句:

[self.navigationController popViewControllerAnimated:YES];

二、在接收信号的controller内(即绑定首页的controller内):

bindAlipayViewController.m中:

创建对应全局变量来接收值:

{
    BOOL _isBind;//绑定状态
    NSString *_bindAlipayAccount;//绑定的支付宝账号
}

跳转方法的实现中:

- (void)jumpToControllerWithType:(NSString *)type{
    if([type intValue]== 1){
        ABFillAlipayViewController *vc=[[ABFillAlipayViewController alloc]init];
        WS(weakself);
        vc.returnBlock = ^(NSDictionary *bindDict) {
            NSLog(@"返回了~");
            // 绑定状态判断
            self->_isBind = [bindDict[@"isBind"] isEqualToString:@"YES"]?YES:NO;
            // 支付宝账号赋值
            self->_bindAlipayAccount = bindDict[@"alipayAccount"];
//            刷新tableView中数据
            [weakself.tableView reloadData];
        };
        
        [self.navigationController pushViewController:vc animated:YES];
    }else if([type intValue]== 2){
        [self.navigationController pushViewController:[[ABRemoveBindAlipayViewController alloc]init] animated:YES];
    }
}

_isBind做判断,等于字符串@“YES”的时候为YES,否则NO。

_bindalipayAccount就等于字典传过来的值。

因为绑定首页使用tableView画的,所以在cell内容中判断,若绑定成功,则做相应改变赋值:

if (_isBind == YES) {
        // 绑定按钮隐藏,显示已绑定按钮
        cell.bindButton.hidden = YES;
        cell.boundButton.hidden = NO;
        // 显示支付宝账号
        cell.subLabel.text = _bindPhoneNumber; 
    }else{
        // 绑定按钮显示,隐藏已绑定按钮
        cell.bindButton.hidden = NO;
        cell.boundButton.hidden = YES;
        // 显示“暂未绑定账号”
        cell.subLabel.text = @“暂未绑定账号”;
    }

作者介绍

  • 李鸿:广州芦苇科技 APP 团队 iOS 开发工程师

内推信息

  • 我们正在招募小伙伴,有兴趣的小伙伴可以把简历发到 app@talkmoney.cn,备注:来自掘金社区
  • 详情可以戳这里--> 广州芦苇信息科技