(有码)UI导航控制器目标动作机制传值

本文介绍了一种在iOS应用中利用目标动作机制实现导航控制器间传值的方法。通过在OneViewController中设置目标动作,当点击第二个页面的返回按钮时,会触发指定方法,将值传递回OneViewController并更新导航栏标题。

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

注意:工程中没有使用系统默认的ViewController.m

目标动作传值

//AppDelegate.m文件

#import "AppDelegate.h"

#import "OneViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

    [self.window makeKeyAndVisible];

    OneViewController *oneViewController = [[OneViewController alloc]init];


    //设置oneViewController为导航控制器的根视图

    UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:oneViewController];

    self.window.rootViewController = nvc;

    return YES;

}


//OneViewController.m文件

#import "OneViewController.h"

#import "TwoViewController.h"

@interface OneViewController ()

@end

@implementation OneViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];


}

//创建第二个导航控制器页面 实现目标动作方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    TwoViewController *twoViewController = [[TwoViewController alloc]init];

    [self.navigationController pushViewController:twoViewController animated:YES];

    [twoViewController addTarget:self action:@selector(titleNameBack:)];

}

//传值

- (void)titleNameBack:(NSString *)string{

    self.navigationItem.title = string;

}


//SecondController.m

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    //创建返回按钮

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(btnClick)];

}

//调用目标动作机制

- (void)btnClick{

    [self.target performSelector:self.action withObject:@"第二个页面"];

    [self.navigationController popViewControllerAnimated:YES];

}

//保存全局变量

- (void)addTarget:(id)target action:(SEL)action{

    _target = target;

    _action = action;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值