通过appDelegate单例,在几个界面直接来回传值,比较简单便捷。
单例在工程中是共享的。。。。
以下代码是点击按钮实现跳转界面,并且通过单例传值实现将子界面中按钮的tittle赋值给导航栏的title。并且在下次点击进入子视图后,和导航栏的title相同的按钮被选中。
#import "ViewController.h"
#import "SubViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor=[UIColor purpleColor];
[self createButtonCilcked];
}
-(void)createButtonCilcked
{
UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
btn.frame=CGRectMake(100, 200, 150, 50);
btn.titleLabel.font=[UIFont systemFontOfSize:25];
[btn setTitle:@"切换" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
btn.backgroundColor=[UIColor orangeColor];
btn.layer.cornerRadius=15;
[btn addTarget:self action:@selector(buttonCilcked:) forControlEvents:UIControlEventTouchUpInside];
btn.tag=100;
[self.view addSubview:btn];
}
-(void)buttonCilcked:(UIButton *)button
{
SubViewController *subView =[[SubViewController alloc]init];
[self.navigationController pushViewController:subView animated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
//获取应用程序的唯一实例并获取应用程序代理对象
AppDelegate *appD =[UIApplication sharedApplication].delegate;
self.navigationItem.title=appD.titleContent;
}
#import "SubViewController.h"
#import "AppDelegate.h"
@interface SubViewController ()
{
AppDelegate *_app;
}
@end
@implementation SubViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor =[UIColor orangeColor];
[self createButtonCilcked];
}
-(void)createButtonCilcked
{
//获取应用程序的唯一实例并获取应用程序代理对象
_app =[UIApplication sharedApplication].delegate;
for (NSInteger i=0; i<3; i++) {
UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
btn.frame=CGRectMake(100, 200+150*i, 150, 50);
btn.titleLabel.font=[UIFont systemFontOfSize:25];
[btn setTitle:[NSString stringWithFormat:@"按钮%li",i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
btn.backgroundColor=[UIColor cyanColor];
btn.layer.cornerRadius=15;
btn.tag=101+i;
[btn addTarget:self action:@selector(buttonCilcked:) forControlEvents:UIControlEventTouchUpInside];
if ([btn.currentTitle isEqualToString:_app.titleContent]) {
btn.selected=YES;
}
[self.view addSubview:btn];
}
}
-(void)buttonCilcked:(UIButton *)button
{
//获取值
_app.titleContent =button.currentTitle;
[self.navigationController popViewControllerAnimated:YES];
}