ios两视图间托付(delegate)传值

本文介绍了一个简单的iOS应用案例,演示了如何在两个视图控制器间进行参数传递及数据返回的过程。具体包括ViewController与ViewController1间的跳转、参数设置、选择数据后返回上一级并更新数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现有两个视图(ViewController。ViewController1),从ViewController中带參数跳转到ViewController1,在ViewController1选中数据后带有效数据后退到ViewController中。托付实现上述功能。

项目:点击下载

一、ViewController主要代码

// button点击事件
-(IBAction)clickSearchBtn:(id)sender {
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    ViewController1 *_viewController = [[[ViewController1 alloc] init] autorelease];
    _viewController.delegate = self;
    _viewController.transText = self.textField.text;
    
    [self.navigationController pushViewController:_viewController animated:YES];
}

// ViewController1Delegate 的代理方法
-(void)selectData:(NSString*)text{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.listArray removeAllObjects];
        for (int i=0; i<5; i++) {
            [self.listArray addObject:[NSString stringWithFormat:@"第%d行数据:%@_%d",i+1,text,arc4random_uniform(100)]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataTableView reloadData];
        });
    });
}

二、 ViewController1主要代码

// ViewController1.h
// delegate写在#import之前,否则可能会Delegate Cannot find protocol declaration
@protocol ViewController1Delegate;
@protocol ViewController1Delegate <NSObject>

@optional
-(void)selectData:(NSString*)text;
@end

// ViewController1.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.delegate respondsToSelector:@selector(selectData:)]) {
        
        //通过托付协议传值
        [self.delegate selectData:[self.listArray objectAtIndex:indexPath.row]];
        [self.navigationController popViewControllerAnimated:YES];
    }
}


三、效果图

  

转载于:https://www.cnblogs.com/liguangsunls/p/6703908.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值