单例传值

//创建单例

@interface Singleton : NSObject

 @property (retain,nonatomic) NSString *info;

+(instancetype)shareInstance;

 @end

 

//单例实现

@implementation Singleton

 

static Singleton *_instance = nil;

 

+(instancetype)shareInstance

{

    if (_instance == nil) {

        _instance = [[super alloc] init];

    }

    return _instance;

}

 

@end

 

 

//  FirstViewController

#import "Singleton.h"

 

@interface FirstViewController : UIViewController<UITextFieldDelegate>

 

@property (strong,nonatomic) UITextField *myText;

@property (strong,nonatomic) NSString *str;

@end

 

 

@implementation FirstViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    self.view.backgroundColor = [UIColor redColor];

    

    self.myText = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];

    self.myText.borderStyle = 2;

    self.myText.backgroundColor = [UIColor redColor];

    [self.view addSubview:self.myText];

    self.myText.delegate = self;

    self.myText.text = self.str;

    

}

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    if ([self.myText isFirstResponder]) {

        [self.myText resignFirstResponder];

        

    }

 

}

 

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

    Singleton *sin = [Singleton shareInstance];

    

     sin.info = self.myText.text;

    NSLog(@"%@,%@",self.myText.text,sin.info);

    [self dismissViewControllerAnimated:YES completion:^{

        

    }];

    return YES;

 

}

 

//  ViewController

#import "FirstViewController.h"

#import "Singleton.h"

 

@interface ViewController : UIViewController<UITextFieldDelegate>

 

@property (strong,nonatomic) UITextField *textF;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.textF = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];

    self.textF.borderStyle = 2;

    self.textF.backgroundColor = [UIColor redColor];

    [self.view addSubview:self.textF];

    self.textF.delegate = self;

    

    

}

 

-(void)viewWillAppear:(BOOL)animated

{

    self.textF.text = [Singleton shareInstance].info;

    

}

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    if ([self.textF isFirstResponder]) {

        [self.textF resignFirstResponder];

        FirstViewController *firstC = [[FirstViewController alloc] init];

        firstC.str = self.textF.text;

        

        [self presentViewController:firstC animated:YES completion:^{

            

        }];

    }

}

 

posted @ 2016-03-15 21:14  原码  阅读(225)  评论(0编辑  收藏  举报