OS学习之——ViewController之间正向传值

下面定义两个页面,为了简单起见,就不添加Btton进行页面跳转,直接点击屏幕,触发
touchesBegan事件,进行页面跳转。

//
// OneViewController.m
// 双向传值
//
// Created by spare on 16/4/16.
// Copyright © 2016年 spare. All rights reserved.
//

#import “OneViewController.h”
#import “TwoViewController.h”

@interface OneViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField1;

@end

@implementation OneViewController

//点击屏幕任意位置,进入页面2
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//初始化将要进入的页面
TwoViewController *vc2=[[TwoViewController alloc]init];
//通过页面2定义的Content属性,将值传给页面2
vc2.content=self.textField1.text;
[self presentViewController:vc2 animated:YES completion:nil];

}
  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

#import <UIKit/UIKit.h>

@interface TwoViewController : UIViewController
//页面1的对象不能直接访问页面2的textField属性
//需要定义一个中间的变量值,将页面一的值保存在中间变量中
@property(nonatomic,copy)NSString *content;

@end

//
// TwoViewController.m
// 双向传值
//
// Created by spare on 16/4/16.
// Copyright © 2016年 spare. All rights reserved.
//

#import “TwoViewController.h”

@interface TwoViewController ()

@property (weak, nonatomic) IBOutlet UITextField *textField2;

@end

@implementation TwoViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

}

//每次进入页面的时候,都去刷新获得的值
-(void)viewWillAppear:(BOOL)animated{
//通过中间属性,传值给textField2;
self.textField2.text=self.content;
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

作者:xuxiaoxie
来源:CSDN
原文:https://blog.csdn.net/xuxiaoxie/article/details/51166729
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/kunga0814/article/details/88909279