iOS_Block界面传值

来源:互联网 发布:全宋词软件下载 编辑:程序博客网 时间:2024/06/07 19:33

使用Block进行界面之间的传值代码比较简洁,下面请看具体代码:

1.创建两个控制器JYRootViewController和JYDetailViewController

2.AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{       self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:[[JYRootViewController alloc]init]];        self.window.rootViewController=nav;    [self.window makeKeyAndVisible];        return YES;}


3.JYRootViewController.m

#import "JYRootViewController.h"#import "JYDetailViewController.h"@interface JYRootViewController ()@property(nonatomic,copy)NSString *name;@end@implementation JYRootViewController- (void)viewDidLoad{    [super viewDidLoad];        self.view.backgroundColor=[UIColor orangeColor];        UIButton *button=[UIButton buttonWithType:UIButtonTypeContactAdd];    button.frame=CGRectMake(100, 100, 100, 30);    [button setTitle:@"跳转" forState:UIControlStateNormal];    [self.view addSubview:button];    [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];    }-(void)click{    JYDetailViewController *detailVc=[[JYDetailViewController alloc]init];    //这里设置detail这个控制器的block属性    detailVc.myBlock=^(NSString *string)    {        self.name=string;        NSLog(@"%@",self.name);    };        [self.navigationController pushViewController:detailVc animated:YES];}


4.JYDetailViewController.h

#import <UIKit/UIKit.h>//定义一个Block代码块typedef void(^MyBlock)(NSString *string);@interface JYDetailViewController : UIViewController//代码块实例@property(nonatomic,copy)MyBlock myBlock;@end

5.JYDetailViewController.m

#import "JYDetailViewController.h"#import "JYRootViewController.h"@interface JYDetailViewController ()@end@implementation JYDetailViewController- (void)viewDidLoad{    [super viewDidLoad];       self.view.backgroundColor=[UIColor greenColor];        UIButton *button=[UIButton buttonWithType:UIButtonTypeContactAdd];    button.frame=CGRectMake(100, 100, 100, 30);    [button setTitle:@"跳转" forState:UIControlStateNormal];    [self.view addSubview:button];    [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];    }-(void)click{    if(self.myBlock)    {        self.myBlock(@"gujinyue");//调用block方法        [self.navigationController popViewControllerAnimated:YES];    }}@end


1 0
原创粉丝点击