extern传值 ios
iOS传值
2017-10-25 21:05:00 weixin_34195546 阅读数 9

A页面跳转到B页面,B页面向A页面传值。

Delegate

A 页面


#import "ViewController.h"
#import "SecondViewController.h"

@interface ViewController ()<ReturnDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下一页" style:UIBarButtonItemStyleDone target:self action:@selector(nextViewController)];
    // Do any additional setup after loading the view, typically from a nib.
}


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

- (void)nextViewController{
    
    SecondViewController *svc = [[SecondViewController alloc]init];
    svc.delegate = self;
    [self.navigationController pushViewController:svc animated:YES];
}

- (void)returnString:(NSString *)string {
    
    NSLog(@"%@",string);
}

@end

B页面

#import <UIKit/UIKit.h>

@protocol ReturnDelegate <NSObject>

- (void)returnString:(NSString *)string;

@end

@interface SecondViewController : UIViewController

@property(nonatomic, weak)id<ReturnDelegate>delegate;

@end


#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(goback)];
    // Do any additional setup after loading the view.
}

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


- (void)goback{
    
    if ([self.delegate respondsToSelector:@selector(returnString:)]) {
        [_delegate returnString:@"6666666"];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#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

Block

A页面

#import "ViewController.h"
#import "SecondViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下一页" style:UIBarButtonItemStyleDone target:self action:@selector(nextViewController)];
    // Do any additional setup after loading the view, typically from a nib.
}


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

- (void)nextViewController{
    
    SecondViewController *svc = [[SecondViewController alloc]init];
    svc.block = ^(NSString *string) {
        NSLog(@"%@",string);
    };
    [self.navigationController pushViewController:svc animated:YES];
}



@end

B页面

#import <UIKit/UIKit.h>

typedef void(^ReturnBlock)(NSString *string);

@interface SecondViewController : UIViewController

@property(nonatomic, copy)ReturnBlock block;

@end

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(goback)];
    // Do any additional setup after loading the view.
}

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


- (void)goback{
    
    if (self.block != nil) {
        self.block(@"66666666");
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#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

Notification

A页面

#import "ViewController.h"
#import "SecondViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下一页" style:UIBarButtonItemStyleDone target:self action:@selector(nextViewController)];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:@"notificationtest" object:nil];
    // Do any additional setup after loading the view, typically from a nib.
}


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

- (void)nextViewController{
    
    SecondViewController *svc = [[SecondViewController alloc]init];
    [self.navigationController pushViewController:svc animated:YES];
}

- (void)receiveNotification:(NSNotification *)noti{
    // NSNotification 有三个属性,name, object, userInfo,其中最关键的object就是从第三个界面传来的数据。name就是通知事件的名字, userInfo一般是事件的信息。
    NSLog(@"%@ === %@ === %@", noti.object, noti.userInfo, noti.name);
}

- (void)dealloc{
    // 移除当前对象监听的事件
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

B页面

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(goback)];
    // Do any additional setup after loading the view.
}

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


- (void)goback{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"notificationtest" object:@"6666666" userInfo:nil];

    [self.navigationController popViewControllerAnimated:YES];
}

/*
#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
ios传值
2017-09-11 16:04:00 weixin_34055787 阅读数 15

一、属性传值

一般用于顺向传递,利用第二个类的属性值来传值,也是最常用的
效果图


1784598-ff023720c6d0c70f.gif
属性传值.gif

shuxingOneViewController.h

shuxingOneViewController.m

#import "shuxingOneViewController.h"

#import "shunxinTwoViewController.h"

@interface shuxingOneViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;//输入框

- (IBAction)btnClick:(id)sender;//按钮

@end

@implementation shuxingOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}
- (IBAction)btnClick:(id)sender {

    shunxinTwoViewController *nextVC = [[shunxinTwoViewController alloc] init];//赋值的控制器
    
    nextVC.name = self.nameTextField.text;//属性传值
    
    [self.navigationController pushViewController:nextVC animated:YES];
}

shunxinTwoViewController.h

#import <UIKit/UIKit.h>
@interface shunxinTwoViewController : UIViewController

@property (nonatomic , strong) NSString *name;

@end

shunxinTwoViewController.m

#import "shunxinTwoViewController.h"

@interface shunxinTwoViewController ()

@property (weak, nonatomic) IBOutlet UILabel *nameLable;//显示上一页传过来的值

@end

@implementation shunxinTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"属性的值--------%@",self.name);
    self.nameLable.text = self.name;
    
}
@end

二、单例传值

单例是共享数据,也可以用来传值,可以顺传也可以逆传,作为传值的话不常用。
效果:


1784598-fb9bd9248c9d219b.gif
单例传值.gif

LocationSingleton.h

#import <Foundation/Foundation.h>

@interface LocationSingleton : NSObject

@property(nonatomic,copy) NSString *namelable;

+(instancetype)shareInstance;

@end

LocationSingleton.m

#import "LocationSingleton.h"

@implementation LocationSingleton

+(instancetype)shareInstance
{
    
    static LocationSingleton *locationSingleton = nil;
    
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        
       locationSingleton = [[self alloc] init];
        
    });
    
    return locationSingleton;
}
@end

DanLiOneVCViewController.h

#import <UIKit/UIKit.h>
@interface DanLiOneVCViewController : UIViewController
@end

DanLiOneVCViewController.m

#import "DanLiOneVCViewController.h"
#import "DanLiTwoViewController.h"

#import "LocationSingleton.h"
@interface DanLiOneVCViewController ()

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

- (IBAction)btnClick:(id)sender;

@end

@implementation DanLiOneVCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}
- (IBAction)btnClick:(id)sender {
    
    //单例传值
    LocationSingleton *singleton  = [LocationSingleton shareInstance];
    singleton.namelable = _nameLable.text;
   
    DanLiTwoViewController *nextVC = [[DanLiTwoViewController alloc] init];
    
    
    [self.navigationController pushViewController:nextVC animated:YES];
    
}
@end

DanLiTwoViewController.h

#import <UIKit/UIKit.h>

@interface DanLiTwoViewController : UIViewController

@end

DanLiTwoViewController.m

#import "DanLiTwoViewController.h"

#import "LocationSingleton.h"

@interface DanLiTwoViewController ()

@property (weak, nonatomic) IBOutlet UILabel *acceptLable;

@end

@implementation DanLiTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //单例接受传值
    LocationSingleton *singleton  = [LocationSingleton shareInstance];
    self.acceptLable.text =  singleton.namelable;

}

三、协议传值

一般逆向传值,比较常用
效果:


1784598-52d3c86b69aadbec.gif
协议.gif

XieYiOneViewController.h

#import <UIKit/UIKit.h>

@interface XieYiOneViewController : UIViewController

@end

XieYiOneViewController.m

#import "XieYiOneViewController.h"
#import "XieYiTwoViewController.h"
@interface XieYiOneViewController ()<XieYiTwoDelegate>

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

- (IBAction)btnClick:(id)sender;

@end

@implementation XieYiOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)btnClick:(id)sender {
    
   XieYiTwoViewController *nextVC = [[XieYiTwoViewController alloc] init];
    
    nextVC.delegate = self;
    
   [self.navigationController pushViewController:nextVC animated:YES];
    
    
}
//协议传值(逆传)
#pragma mark -XieYiTwoDelegate
-(void)ChangeViewController:(XieYiTwoViewController *)viewController changeText:(NSString *)text
{
  
    self.telePhoneField.text = text;

}

XieYiTwoViewController.h

#import <UIKit/UIKit.h>


@class XieYiTwoViewController;

@protocol XieYiTwoDelegate <NSObject>

- (void)ChangeViewController:(XieYiTwoViewController *)viewController  changeText:(NSString *)text;

@end

@interface XieYiTwoViewController : UIViewController

@property (nonatomic,weak) id <XieYiTwoDelegate> delegate;

@end

XieYiTwoViewController.m

#import "XieYiTwoViewController.h"

@interface XieYiTwoViewController ()

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

- (IBAction)btnClick:(id)sender;

@end

@implementation XieYiTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

//协议传值
- (IBAction)btnClick:(id)sender {
    
    if ([self.delegate respondsToSelector:@selector(ChangeViewController:changeText:)]) {
        
        [self.delegate ChangeViewController:self changeText:self.telePhonefield.text];
    
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end

四、block传值

感觉block传值是最爽的,发现现在的demo中大部分都在用block了,一般用来逆向传值,使用频率较高。
效果:
BlockOneViewController.h

#import <UIKit/UIKit.h>

@interface BlockOneViewController : UIViewController

@end

BlockOneViewController.m

#import "BlockOneViewController.h"

#import "BlockTwoViewController.h"
/*
 block要掌握
 1>如何定义一block
 2>如何利用block封装一段代码
 3>block如何访问外部变量
 4>利用typedef定义一个block的类型
 
*/

//用typedef定义一个block类型的变量

typedef  int(^MyBlock)(int , int);

@interface BlockOneViewController ()

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

@property (strong , nonatomic) NSMutableArray *arrayVlues;

- (IBAction)BtnClick:(id)sender;

@end

@implementation BlockOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //什么是block?
    //block用来保存一段代码
    //跟函数很像,有返回值,有参数
    //是一个数据类型
    
//    [self block1];
//    [self block2];
//    [self block3];
//    [self block4];
    
    //传一个数组
//    self.arrayVlues = [NSMutableArray array];
//    NSLog(@"arrayVlues1 = %@",self.arrayVlues);
//    NSLog(@"arrayVlues1 = %p",self.arrayVlues);
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    NSLog(@"arrayVlues2 = %@",self.arrayVlues);
//    NSLog(@"arrayVlues2 = %p",self.arrayVlues);
    
    
}
//1、没有返回值,没有参数
-(void)block1
{
    
    void(^myBlock1)() = ^(){
        
        NSLog(@"---------block代码------");
        
    };
    
   // int a = 10;
    //利用block变量调用block块内的代码
    myBlock1();

}
//有返回值,有形参
-(void)block2
{

    int (^addBlock)(int , int) =
    
    ^(int a,int b){
    
        return a + b;
    
    };

    NSLog(@"------加法=%d-----",addBlock(10,20));
}
//block的访问权限
-(void)block3
{
    int a = 10;
    
   __block int b = 20;
    void(^addBlock)();
    
    addBlock = ^
    {
       //1、block可以访问外部的变量
        NSLog(@"访问外部的变量a = %d",a);
        
        
      //2、默认情况下,不能修改外部的变量
        
       // a = 20;
      //3、给局部变量加上关键字__block,就可以修改了
        b = 25;
        NSLog(@"访问局部的变量b = %d",b);
    };
    
    addBlock();
    
}
//使用typedef定义block类型
-(void)block4
{
    //加法
    int (^SumBlock)(int, int);
    
    SumBlock = ^(int a ,int b)
    {
    
        return a + b;
    
    };

    //减法
    int (^jianfaBlock)(int, int) = ^(int a ,int b)
    {
    
        return a-b;
    
    };
     NSLog(@"加--------%d,减--------%d",SumBlock(7,8),jianfaBlock(8, 7));
    //改造代码,定义一个block类型的变量
    
    
    MyBlock sunBlock1;
    
    sunBlock1 = ^(int a ,int b)
    {
        
        return a + b;
        
    };
    
    //减法
    MyBlock jianfaBlock1 = ^(int a ,int b)
    {
        
        return a-b;
        
    };

     NSLog(@"改造加--------%d,改造减--------%d", sunBlock1(7,8),jianfaBlock1(8, 7));
    
    

}
//block传值
- (IBAction)BtnClick:(id)sender {
    
//第一种写法
//    BlockTwoViewController *nextVC = [[BlockTwoViewController alloc] init];
//    [nextVC returnText:^(NSString *showText) {
//        
//        
//        self.nameLable.text = showText;
//        
//        
//    }];

    BlockTwoViewController *secondVC = [[BlockTwoViewController alloc] init];
//    __weak BlockOneViewController *firstVC = self;
    
    
    secondVC.returnTextBlock = ^(NSArray *strArr){
        
        NSLog(@"-strARR--%@",strArr);
        
    };
    
//    BlockTwoViewController *secondVC = [[BlockTwoViewController alloc] init];
//    
//    
//    secondVC.rceiverVlues = self.arrayVlues;
//    
    [self.navigationController pushViewController:secondVC animated:YES];
}

BlockTwoViewController.h

#import <UIKit/UIKit.h>
//为要声明的Block重新定义了一个名字
//定义声明Block属性

typedef  void(^ReturnTextBlock)(NSArray *showTextArr);
@interface BlockTwoViewController : UIViewController
@property (nonatomic, copy) ReturnTextBlock returnTextBlock;//定义一个Block属性
//写一个方法
//- (void)returnText:(ReturnTextBlock)block;
@end

BlockTwoViewController.m

#import "BlockTwoViewController.h"

@interface BlockTwoViewController ()

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

@property (weak, nonatomic) IBOutlet UILabel *acceptLable;

- (IBAction)btnClick:(id)sender;

@end

@implementation BlockTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}
//第一种写法
//- (void)returnText:(ReturnTextBlock)block
//{
//
//    self.returnTextBlock = block;
//   
//}
////当视图将要消失的时候传值
//- (void)viewWillDisappear:(BOOL)animated {
//    
//    if (self.returnTextBlock != nil) {
//        
//        self.returnTextBlock(self.name1TextField.text);
//    }
//}
//第二种写法
- (IBAction)btnClick:(id)sender {
    
    NSArray *showTextArr = @[@"a",@"b"];
    
    self.returnTextBlock(showTextArr);
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end

五、通知传值

通知传值,我一般很少用
效果图:

1784598-3cacfdfcdd6d853c.gif
通知.gif

tongzhiOneViewController.h

#import <UIKit/UIKit.h>

@interface tongzhiOneViewController : UIViewController

@end

tongzhiOneViewController.m

#import "tongzhiOneViewController.h"

#import "tongzhiTwoViewController.h"

@interface tongzhiOneViewController ()

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

- (IBAction)btnClick:(id)sender;


@end

@implementation tongzhiOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     //注册通知
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:)name:@"tongzhi" object:nil];
}
- (void)tongzhi:(NSNotification *)text{
    
    NSLog(@"%@",text.userInfo[@"textOne"]);
    
    NSLog(@"-----接收到通知------");
    
    _nameLable.text = text.userInfo[@"textOne"];
}


- (IBAction)btnClick:(id)sender {
    
    tongzhiTwoViewController *secondVC = [[tongzhiTwoViewController alloc] init];
    [self.navigationController pushViewController:secondVC animated:YES];
}
//移除通知
- (void)dealloc
{
   //1、
   // [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    //2、
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:self];
    
}

tongzhiTwoViewController.h

#import <UIKit/UIKit.h>

@interface tongzhiTwoViewController : UIViewController

@end

tongzhiTwoViewController.m

#import "tongzhiTwoViewController.h"

@interface tongzhiTwoViewController ()

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

- (IBAction)btnClick:(id)sender;


@end

@implementation tongzhiTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
//通知传值
- (IBAction)btnClick:(id)sender {
    //1、添加 字典,将label的值通过key值设置传递
    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:self.nameLable.text,@"textOne", nil];
    //2、创建通知
    NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
    //3、通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    [self.navigationController popViewControllerAnimated:YES];
    
}
@end

补充:
第一次使用gif图片,下面介绍一款好用的gif图片生成工具
GIf 图片的制制作——GIFBrewery

2017-12-13 15:13:28 weixin_34050389 阅读数 3

在iOS中传值的方式有很多种方式,有最普遍的就是属性传值,代理传值,block传值等方式了。 写了OCswift的两个版本的传值demo。

其中需要说明一下的是,这个通知传值。 在通知传值的时候,有的时候会出现如下的问题,也就是当通知中心发出了通知,接收通知的一方却没有收到任何消息。这可能是线程阻塞的原因,只需要将通知中心放在子线程中去处理。

// OC
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self userInfo:@{@"text" : @"请输入账号名"}];
}];
// swift
OperationQueue.main.addOperation {
    let cell = self.tableView.cellForRow(at: IndexPath(row: 4, section: 0))
    let wjNotificationName = Notification.Name.init(rawValue: "notificationTest")
    NotificationCenter.default.post(name: wjNotificationName, object: self, userInfo: ["text" : cell?.textLabel?.text ?? "没有值传入"])
}
复制代码

单例传值: 在OC和swift中创建单例传值,一般都会创建一个单例类,通过这个单例类来中转,进行传值,也就是说这个单例类就像是个容器一样进行存储数据,也就是说正向反向传值都可以。 但是在OC中和swift中创建单例类还是有些不同:

// OC采用的是GCD或者是其他的方法进行创建
+ (wjSingleTon *)shareSingleTon {
    static wjSingleTon *singleTon = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        singleTon = [[self alloc] init];
    });
    return singleTon;
}

// swift创建单例类
// MARK:- 单例类
final class wjSingleTon: NSObject {
    static let sharedInstance = wjSingleTon()
    var text : String!
    override init() {}
}
复制代码

其他的传值方式在oc和swift中没有多大的差别。

2016-03-14 15:17:00 weixin_34008805 阅读数 3

iOS 传值

一、属性传值(省略)

二、代理传值 RootViewController <- FirstViewController

RootViewController界面代码:

.m文件
#import "RootViewController.h"
#import "FirstViewController.h"
@interface RootViewController ()<FirstViewControllerDelegate>//第四步
@end

-(void)buttonAction:(UIButton *)sender{
    FirstViewController *fvc = [[FirstViewController alloc]init];
    fvc.delegate = self;//第五步
    fvc.text = self.textField.text;
    [self.navigationController pushViewController:fvc animated:YES];
}
-(void)sendValue:(NSString *)str{//第六步
    self.textField.text = str;
}

FirstViewController界面代码:

.h文件
#import <UIKit/UIKit.h>
@protocol FirstViewControllerDelegate <NSObject>//第一步
//协议方法
-(void)sendValue:(NSString *)str;
@end

@interface FirstViewController : UIViewController
@property (nonatomic,assign)id<FirstViewControllerDelegate> delegate;//第二步
@end

.m文件
-(void)buttonAction:(UIButton *)sender{//第三步
    if ([self.delegate respondsToSelector:@selector(sendValue:)]) {
        [self.delegate sendValue:self.textField.text];
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}

三、Block传值   RootViewController <- FirstViewController

RootViewController界面代码:

-(void)buttonAction:(UIButton *)sender{
    FirstViewController *fvc = [[FirstViewController alloc]init];
    [fvc sendText:^(NSString *str) {//第六步
        self.textField.text = str;
    }];
    [self.navigationController pushViewController:fvc animated:YES];
}

FirstViewController界面代码:

FirstViewController.h
#import <UIKit/UIKit.h>

typedef void(^SENDBLOCK)(NSString *str);//第一步

@interface FirstViewController : UIViewController

@property (nonatomic,copy)SENDBLOCK block;//第二步
-(void)sendText:(SENDBLOCK)block;//第三步
@end

FirstViewController.m
-(void)buttonAction:(UIButton *)sender{
    if (self.block != nil) {//第四步
        self.block(self.textField.text);
    }
    [self.navigationController popToRootViewControllerAnimated:YES]; 
}
-(void)sendText:(SENDBLOCK)block{//第五步
    self.block = block;
}


四、单例传值  双向的

RootViewController界面代码:

.m
#import "RootViewController.h"
#import "FirstViewController.h"
#import "DataManager.h"

@interface RootViewController ()

@end

@implementation RootViewController

-(void)viewWillAppear:(BOOL)animated{
   self.textField.text = [DataManager shareDataManager].text;
}
-(void)buttonAction:(UIButton *)sender{
    [DataManager shareDataManager].text = self.textField.text;
    
    FirstViewController *fvc = [[FirstViewController alloc]init];
    [self.navigationController pushViewController:fvc animated:YES];
}

FirstViewController界面代码:

#import "FirstViewController.h"
#import "DataManager.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
-(void)viewWillAppear:(BOOL)animated{
    self.textField.text = [DataManager shareDataManager].text;
}
-(void)buttonAction:(UIButton *)sender{
    [DataManager shareDataManager].text = self.textField.text;
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

DataManager 单例类代码:

.h文件
#import <Foundation/Foundation.h>
@interface DataManager : NSObject
@property (nonatomic,strong)NSString *text;

+(instancetype)shareDataManager;
@end
.m文件
#import "DataManager.h"

static DataManager *_dataManager = nil;

@implementation DataManager

+(instancetype)shareDataManager{
    return [[self alloc]init];
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_dataManager == nil) {
            _dataManager = [super allocWithZone:zone];
        }
    });
    return _dataManager;
}
@end

五、通知传值

RootViewController 界面代码:

.m 文件
-(void)dealloc{
//移除通知
[[UIApplication sharedApplication] cancelAllLocalNotifications];

}
- (void)viewDidLoad { 
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postNotification:) name:@"Notification" object:nil];
}
//实现通知方法
-(void)postNotification:(NSNotification *)sender{
    self.view.backgroundColor = [UIColor grayColor];
}

FirstViewCOntroller 界面代码:

.m 文件
#import "FirstViewController.h"

@interface FirstViewController ()

@end
@implementation FirstViewController

-(void)buttonAction:(UIButton *)sender{
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:nil];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}


转载于:https://my.oschina.net/GeeksChen/blog/637112

2014-11-06 00:06:49 ITyanping 阅读数 481

属性传值 将A页面所拥有的信息通过属性传递到B页面使用

B页面定义了一个naviTitle属性,在A页面中直接通过属性赋值将A页面中的值传到B页面。


A页面DetailViewController.h文件

#import <UIKit/UIKit.h>

#import "DetailViewController.h"

@interface RootViewController :UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end


A RootViewController.m页面实现文件

#import "RootViewController.h"

#import "DetailViewController.h"


@interface RootViewController ()

@end

@implementation RootViewController

//核心代码

-(void)loadView

{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

    tf = (UITextField *)[self.viewviewWithTag:1000];

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    

    DetailViewController *detailViewController = [[DetailViewControlleralloc]init];

    //属性传值,直接属性赋值

    detailViewController.naviTitle =tf.text;

    //导航push到下一个页面

    [self.navigationControllerpushViewController:detailViewController animated:YES];

    [detailViewControllerrelease];   

}


B页面DetailViewController.h文件

#import <UIKit/UIKit.h>

@interface DetailViewController :UIViewController

{

   UITextField *textField;

   NSString *_naviTitle;

}

@property(nonatomic,retain)NSString *naviTitle;

@end


B页面.m实现文件

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

@synthesize naviTitle =_naviTitle;

-(void)loadView

{

    self.view = [[[UIViewalloc]initWithFrame:CGRectMake(0,0320,480)]autorelease];

   self.title = self.naviTitle ;    

}


代理传值 

A页面push到B页面,如果B页面的信息想回传(回调)到A页面,用用代理传值,其中B定义协议和声明代理,A确认并实现代理,A作为B的代理

A页面RootViewController.h文件

#import <UIKit/UIKit.h>

#import "DetailViewController.h"

@interface RootViewController : UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end


A页面RootViewController.m实现文件

#import "RootViewController.h"

#import "DetailViewController.h"


@interface RootViewController ()

@end

@implementation RootViewController

//核心代码

-(void)loadView

{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    //A页面push到B页面

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

    tf = (UITextField *)[self.view viewWithTag:1000];

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    DetailViewController *detailViewController = [[DetailViewController alloc]init]; 

     //代理传值

   detailViewController.delegate =self;//让其自身作为代理人

    //导航push到下一个页面

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];   

}

//实现代理方法

-(void)changeTitle:(NSString *)aStr

{

    tf = (UITextField *)[self.view viewWithTag:1000];

    tf.text = aStr;//将从B页面传入的参数赋给A页面中的TextField

   tf.text = aStr;

}

B页面DetailViewController.m文件

#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController

{

    UITextField *textField;

    //定义代理

  id<ChangeDelegate>_delegate;

}

@property(nonatomic,assign)id<ChangeDelegate> delegate;

@end

//定义协议

@protocol ChangeDelegate <NSObject>

-(void)changeTitle:(NSString *)aStr;//协议方法

@end



B页面DetailViewController.h实现文件

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

-(void)loadView

{

    self.view = [[[UIView alloc]initWithFrame:CGRectMake(00320480)]autorelease];

    UIBarButtonItem *doneItem = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:selfaction:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItemrelease];

}

//pop回前一个页面

-(void)doneAction:(id)sender

{

   if (self.delegate && [self.delegaterespondsToSelector:@selector(changeTitle:)])//若代理存在且响应了changeTitle这个方法

    {

        //[self.delegate changeTitle:textField.text];

        [self.delegatechangeTitle:textField.text];//textField.text参数传给changeTitle方法  让代理,也就是A页面去实现这个方法

        NSLog(@"%@",self.navigationController.viewControllers);

        [self.navigationControllerpopViewControllerAnimated:YES];

    }

}



单例传值(实现共享)


AppStatus.h  创建一个单例类 AppStatus

#import <Foundation/Foundation.h>


@interface AppStatus : NSObject

{

    NSString *_contextStr;

}

@property(nonatomic,retain)NSString *contextStr;
 

+(AppStatus *)shareInstance;


@end

AppStatus.m 
 

#import "AppStatus.h"


@implementation AppStatus

@synthesize contextStr = _contextStr;


static AppStatus *_instance = nil;

+(AppStatus *)shareInstance

{

    if (_instance == nil)

    {

        _instance = [[super alloc]init];

    }

    return _instance;

}


-(id)init

{

    if (self = [super init])

    {

        

    }

    return  self;

}


-(void)dealloc

{

    [super dealloc];

}


@end


A页面RootViewController.h


#import 
"RootViewController.h"

#import "DetailViewController.h"

#import "AppStatus.h"


@interface RootViewController ()


@end


@implementation RootViewController

-(void)loadView

{
    //核心代码 

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

     

    tf = (UITextField *)[self.view viewWithTag:1000];

    

 //单例传值  将要传递的信息存入单例中(共享中)

  //  [[AppStatus shareInstance]setContextStr:tf.text]; 跟下面这种写法是等价的

    [AppStatus shareInstance].contextStr = tf.text;

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    

    DetailViewController *detailViewController = [[DetailViewController alloc]init];

    

    //导航push到下一个页面

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];

} 
@end
 

B页面
DetailViewController.h


#import <UIKit/UIKit.h>

@protocol ChangeDelegate;//通知编译器有此代理


@interface DetailViewController : UIViewController

{

    UITextField *textField;

}

@end



B页面DetailViewController.m

#import "DetailViewController.h"

#import "AppStatus.h"


@interface DetailViewController ()


@end


@implementation DetailViewController

@synthesize naviTitle = _naviTitle;


-(void)loadView

{

    self.view = [[[UIView alloc]initWithFrame:CGRectMake(00320480)]autorelease];

    

    //单例

    self.title = [AppStatus shareInstance].contextStr;

    

    

    textField = [[UITextField alloc]initWithFrame:CGRectMake(10010015030)];

    textField.borderStyle = UITextBorderStyleLine;

    [self.view addSubview:textField];

    [textField release];


    UIBarButtonItem *doneItem = [[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:self action:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItem release];

    

}

//这个方法是执行多遍的  相当于刷新view

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    

    tf = (UITextField *)[self.view viewWithTag:1000];

    tf.text = [AppStatus shareInstance].contextStr;

     

}

//pop回前一个页面

-(void)doneAction:(id)sender

{

    //  单例传值

    [AppStatus shareInstance].contextStr = textField.text;

    [self.navigationController popToRootViewControllerAnimated:YES];

} 

 
通知传值 谁要监听值的变化,谁就注册通知  特别要注意,通知的接受者必须存在这一先决条件


A页面RootViewController.h

#import <UIKit/UIKit.h>

#import "DetailViewController.h"


@interface RootViewController : UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end 
 

A页面RootViewController.m
 

#import "IndexViewController.h"

#import "DetailViewController.h"

#import "AppStatus.h"



@implementation IndexViewController


-(void)dealloc

{

    [[NSNotificationCenter defaultCenterremoveObserver:self

                                                    name:@"CHANGE_TITLE" object:nil];

    [super dealloc];

}


-(id)init

{

    if (self = [super init])

    {

        [[NSNotificationCenter defaultCenteraddObserver:self

                                                 selector:@selector(change:)

                                                     name:@"CHANGE_TITLE"

                                                   object:nil];

    }

    return self;

}


-(void)change:(NSNotification *)aNoti

{

    // 通知传值

    NSDictionary *dic = [aNoti userInfo];

    NSString *str = [dic valueForKey:@"Info"];

    

    

    UITextField *tf =  (UITextField *)[self.view viewWithTag:1000];

    tf.text = str;

}

 


-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    

    /*

    // 单例传值

    UITextField *tf =  (UITextField *)[self.view viewWithTag:1000];

    tf.text = [AppStatus shareInstance].contextStr;

    */

}

@end

DetailViewController.h
 

#import <UIKit/UIKit.h>

@protocol ChangeDelegate;//通知编译器有此代理


@interface DetailViewController : UIViewController

{

    UITextField *textField;

}

@end


 DetailViewController.m


#import "DetailViewController.h"

#import "AppStatus.h"



@implementation DetailViewController

@synthesize naviTitle = _naviTitle;


-(void)loadView

{

    

    UIBarButtonItem *doneItem = [[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:self action:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItem release];

}

// pop回前一个页面

-(void)doneAction:(id)sender

{

    

NSDictionary *dic = [NSDictionary dictionaryWithObject:textField.text forKey:@"Info"];


[[NSNotificationCenter defaultCenterpostNotificationName:@"CHANGE_TITLE" object:nil userInfo:dic];


[self.navigationController popViewControllerAnimated:YES];


}


Block

几种形式的Block

    //无返回值
    void (^block1) (void);
    block1 = ^{
        NSLog(@"bock demo");
    };
    block1();
    
    //int返回类型
    int (^block2) (void);
    block2  = ^(void)
    {
        int a  = 1 ,b =1;
        int c = a+b;
        return  c;
    };
    
    //有返回 有参数
    int (^block3)(int, int)= ^(int a, int b)
    {
        int c = a +b;
        return c;
        
    };
    NSLog(@"bock=%d",block3(1,2));
    
    //有返回值,有参数并且可以修改block之外变量的block
    static int sum = 10;// __blcik and static关键字 或者 _block int sum = 10
    int (^block4) (int) =^(int a)
    {
        sum=11;
        int c = sum+a;   //此时sum就是可以修改的了,若没加static或_block关键字则不能修改block之外变量
        return c;
    };
    NSLog(@"block4= %d",block4(4));


Block传值

例如A(Ablock)页面的值传道B(Bblock)页面  


在A页面中ABlock.h

@interface Ablock : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableview;
    UILabel *labe;
    UIImageView *imagevies;
}
@end


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableview deselectRowAtIndexPath:indexPath animated:YES];
    
    Bblcok *bblock = [[Bblcok alloc] initwithBlock:Block_copy(^(NSString *aBlock){    
        labe.text = aBlock;
        NSLog(@"%@",aBlock);

    })];
    

    bblock.imgeviews = imagevies.image;
    bblock.String = labe.text;
    [self.navigationController pushViewController:bblock animated:YES];
    [bblock release];
}



在A页面中Bblock.h

#import <UIKit/UIKit.h>
typedef  void (^MyBlock) (NSString *);
@interface Bblcok : UIViewController
{
    UIImageView *image;
    UITextField *aField;
    UIButton *aButt;
    NSString *_String;
    id _imgeviews;
    MyBlock myBlock;
}
@property(nonatomic,copy)MyBlock myBlock;   
@property(nonatomic,retain) id imgeviews;
@property(nonatomic,retain) NSString *String;
-(id)initwithBlock:(MyBlock)aBlcok;
@end


//
//  Bblcok.m
//  Blcok
//
//  Created by zhu  on 13-8-12.
//  Copyright (c) 2013年 Zhu Ji Fan. All rights reserved.
//

#import "Bblcok.h"

@interface Bblcok ()

@end

@implementation Bblcok
@synthesize imgeviews = _imgeviews , String = _String;
@synthesize myBlock = _myBlock;
-(id)initwithBlock:(MyBlock)aBlcok
{
    if (self = [super init])
    {
        self.myBlock = aBlcok; 
    }
    return self;
}

-(void) dealloc
{
    [super dealloc];
}

-(void) loadView
{
    UIControl *cont = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 568-44)];
    [cont addTarget:self action:@selector(Clcik) forControlEvents:UIControlEventTouchUpInside];
    self.view = cont;
    
    aField = [[UITextField alloc] initWithFrame:CGRectMake(60, 10, 160, 30)];
    aField.borderStyle = UITextBorderStyleLine;
    aField.placeholder = self.String;
    [self.view addSubview:aField];
    
    aButt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    aButt.frame = CGRectMake(60, 50, 70, 30);
    [aButt setTitle:@"修改" forState:0];
    [aButt addTarget:self action:@selector(aButtClcik:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:aButt];
    
    image = [[UIImageView alloc] initWithFrame:CGRectMake(60, 100, 210, 260)];
    image.backgroundColor = [UIColor blueColor];
    image.image = self.imgeviews;
    [self.view addSubview:image];
    [image release];

}

-(IBAction)aButtClcik:(id)sender
{
    NSString *sting = aField.text;
    myBlock(sting);
    [self.navigationController popToRootViewControllerAnimated:YES];
}


-(void)Clcik
{
    [aField resignFirstResponder];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

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

iOS 传值

阅读数 381

iOS 传值

阅读数 240

iOS 传值

阅读数 6

iOS传值

阅读数 4

ios 传值

阅读数 11

没有更多推荐了,返回首页