在iOS开发中传值是一个非常经典的方法,有六种传值方式:属性传值、代理传值、Block传值、方法传值、单例传值、通知传值。本章就来分享一下通过Block完成两个不同界面间的传值操作。
首先再来了解一下Block,简单一点说,Block就是一段匿名的代码块,是具有某种功能的代码块。那么接下来通过实际应用场景,来直观的演示一下用Block传值的操作,具体如下所示。
实例场景是在控制器A里面点击按钮进入到控制器B中,控制器B里面是一个单元格界面,每一个列表对应的三个参数,需要选中其中想要的列表然后返回并传值到控制器A里面,这就是整个使用场景的描述,接下来是具体实现的代码步骤。
控制器A里面按钮点击事件的写法如下:
- (void)popoutBtnClick {
//跳转到控制器B
TeaMineBluetoothController *histoyVC = [TeaMineBluetoothController new];
[self.navigationController pushViewController:histoyVC animated:YES];
histoyVC.Complate = ^(NSString *temp, NSString *time, NSString *water) {
//Block传的三个参数给控制器A赋值的地方
_centigradeDegree = [temp floatValue];
_timeDegree = [time floatValue];
_waterDegree = [water floatValue];
};
}
控制器B.h文件里面,需要声明Block函数,需要传三个参数值,具体如下所示:
#import "BaseViewController.h"
@interface TeaMineBluetoothController : BaseViewController
@property (nonatomic, copy) void(^Complate)(NSString *temp, NSString *time, NSString *water);
@end
控制器B.m文件里面,主要是在单元格的点击事件里面给Block里面的参数赋值,具体步骤如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (_selectedIndexPath && _selectedIndexPath.row == indexPath.row) {
_selectedIndexPath = nil; // 点击了已经选中的列表项 , 取消选中
}else {
_selectedIndexPath = indexPath;
NSDictionary *dic = _dateSource[indexPath.row];
NSString *tempValue = dic[@"Temp"];
NSString *timeValue = dic[@"Time"];
NSString *waterValue = dic[@"Water"];
NSString *title = NSLocalizedString(@"Title", nil);
NSString *bluetooth = NSLocalizedString(@"Choose Success!", nil);
NSString *confirm = NSLocalizedString(@"Confirm", nil);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:bluetooth preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Block的赋值地方
if (_Complate) {
_Complate(tempValue, timeValue, waterValue); //直接给Block里面的三个参数赋值
}
[self.navigationController popViewControllerAnimated:YES];
}];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
[self.tableView reloadData]; // 数据加载完成之后刷新tableview
}
}
这就是通过Block进行的一个简单传值操作。
以上就是本章的全部内容,欢迎关注三掌柜的微信公众号“程序猿by三掌柜”,三掌柜的新浪微博“三掌柜666”,欢迎关注!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有