iOS传值的方法-单例反向传值

来源:互联网 发布:中国加工贸易数据 编辑:程序博客网 时间:2024/06/05 04:55

iOS传值,用单例进行反向传值,将B界面的值传到A界面。


1、A类中的代码如下:

#import "FirstViewController.h"#import "SecondViewController.h"#import "DataSource.h"@interface FirstViewController ()@property (retain,nonatomic) UILabel *label;@end@implementation FirstViewController@synthesize label;- (void)viewDidLoad {    [super viewDidLoad];        self.view.backgroundColor = [UIColor whiteColor];    self.title = @"单例反向传值";            label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, 30)];    label.text = @"点击按钮";    [self.view addSubview:label];        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 200, self.view.frame.size.width-20, 35)];    btn.backgroundColor = [UIColor grayColor];    [btn setTitle:@"确定" forState:UIControlStateNormal];    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btn];}- (void)viewWillAppear:(BOOL)animated {    DataSource *dataSource = [DataSource sharedDataSource];    if ([dataSource.myName length] != 0) {        self.label.text = dataSource.myName;        dataSource.myName = @"";    }}- (void)btnClick:(id)sender {        SecondViewController *second = [[SecondViewController alloc] init];    [self.navigationController pushViewController:second animated:YES];    }@end

2、B类中的代码如下:

#import "SecondViewController.h"#import "DataSource.h"@interface SecondViewController ()@property (retain, nonatomic) UITextField *textField;@end@implementation SecondViewController@synthesize textField;- (void)viewDidLoad {    [super viewDidLoad];        self.view.backgroundColor = [UIColor whiteColor];          textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, 30)];    textField.borderStyle = UITextBorderStyleRoundedRect;    [self.view addSubview:textField];        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 150, self.view.frame.size.width-20, 35)];    btn.backgroundColor = [UIColor grayColor];    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btn];        }- (void)btnClick:(id)sender {    DataSource *dataSource = [DataSource sharedDataSource];    dataSource.myName = self.textField.text;    [self.navigationController popViewControllerAnimated:YES];}@end

3、添加一个新类 DataSource 

#import <Foundation/Foundation.h>@interface DataSource : NSObject@property (nonatomic, strong) NSString *myName;+(DataSource*)sharedDataSource;@end

#import "DataSource.h"@implementation DataSource+(DataSource *)sharedDataSource{    static DataSource *dataSource = nil;    static dispatch_once_t once;    dispatch_once(&once, ^{        dataSource = [DataSource new];    });    return dataSource;}@end

4、截图如下:

    


5、Demo下载地址: http://download.csdn.net/detail/u010545480/8915849

0 0
原创粉丝点击