iOS筆記之五種頁(yè)面?zhèn)髦捣绞?/h1>

在說頁(yè)面?zhèn)髦抵跋扔涗浺幌卤容^有意思的跳轉(zhuǎn):
業(yè)務(wù)場(chǎng)景:現(xiàn)有一個(gè)頁(yè)面跳轉(zhuǎn)順序?yàn)椋篈-B-C-D噩咪,今需要在C push到D之后妹懒,把Cpop出來(lái)篓叶,達(dá)到頁(yè)面順序?yàn)椋篈-B-D艺玲。

可能有看官會(huì)說肋僧,這很簡(jiǎn)單鞍呤ぁ:在C push到D之前,先在C里面pop一次就可以了啊嫌吠,你盡管去試止潘,能到達(dá)效果算我輸!

這里有兩種方案:
第一種:重寫D的pop方法居兆,指定他pop到特定頁(yè)面也就是D覆山,但是這里會(huì)有一個(gè)問題,如果有多個(gè)頁(yè)面都能push到D泥栖,你這里指定pop到特定頁(yè)面就會(huì)出問題簇宽,比如上面是A-B-D,指定D pop到B吧享,如果有頁(yè)面E-F-D的跳轉(zhuǎn)魏割,這里D pop顯然是要回到F,而不是指定的B钢颂,也有人會(huì)說钞它,那pop就分類討論,分別pop到指定頁(yè)面殊鞭,但是這種方案顯然是比較麻煩的遭垛,有興趣的可以試一試。

第二種:直接操作導(dǎo)航棧操灿,在需要跳轉(zhuǎn)的位置锯仪,先把C從導(dǎo)航棧移除,然后再把D放入趾盐,完美的解決了我們的問題庶喜。

//C.m
D *result = [[D alloc] init];
NSMutableArray *vcs = self.navigationController.viewControllers.mutableCopy;
[vcs removeLastObject];
[vcs addObject:result];
[self.navigationController setViewControllers:vcs animated:YES];


進(jìn)入正題:
頁(yè)面?zhèn)髦凳呛艹S玫囊粋€(gè)東西救鲤,這里介紹比較常用的五種:屬性傳值久窟,block傳值,代理傳值,單例傳值队他,通知傳值锡凝。
(一)屬性傳值
實(shí)踐方案:第二個(gè)界面中的lable顯示第一個(gè)界面textField中輸入的文本
實(shí)踐步驟:
首先我們建立一個(gè)RootViewControllers和一個(gè)DetailViewControllers(detail頁(yè)面的label顯示root頁(yè)面textField輸入的內(nèi)容)张肾,在DetailViewControllers中聲明一個(gè)textString屬性,用于接收傳過來(lái)的字符串:

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

@interface DetailViewControllerOne : UIViewController

@property (nonatomic , strong) NSString *textString;

@end

同時(shí)創(chuàng)建一個(gè)Lable用來(lái)顯示傳過的字符串

//DetailViewControllerOne.m
#import "DetailViewControllerOne.h"

@interface DetailViewControllerOne ()

@end

@implementation DetailViewControllerOne

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, CGRectGetWidth(self.view.bounds)-40, 30)];
    label.backgroundColor = [UIColor orangeColor];
    label.font = [UIFont systemFontOfSize:20];
    label.numberOfLines = 0;
    label.text = self.textString;  //使用傳遞過來(lái)的值
    [self.view addSubview:label];
    self.view.backgroundColor = [UIColor greenColor];
}

在RootViewControllers上引入DetailViewControllers同時(shí)聲明一個(gè)textField屬性用來(lái)輸入字符串

//RootViewControllers.m
#import "RootViewControllerOne.h"
#import "DetailViewControllerOne.h"

@interface RootViewControllerOne ()

@property(nonatomic , strong) UITextField *textField;

@end

@implementation RootViewControllerOne

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"屬性傳值";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.textField];
    
    // 創(chuàng)建一個(gè)輕拍手勢(shì)锚扎,當(dāng)點(diǎn)擊屏幕任何一個(gè)地方吞瞪,就取消鍵盤的第一響應(yīng),隱藏鍵盤
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self.view addGestureRecognizer:tap];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 200, CGRectGetWidth(self.view.bounds)-40, 40);
    [button setTitle:@"下一頁(yè)" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:20];
    button.backgroundColor = [UIColor greenColor];
    
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, CGRectGetWidth(self.view.bounds)-40, 40)];
        _textField.backgroundColor = [UIColor greenColor];
        _textField.placeholder = @"請(qǐng)輸入內(nèi)容";
        
    }
    return _textField;
}

//放棄作為第一響應(yīng)者
- (void)handleTap:(id)sender {
    [_textField resignFirstResponder];
}

//頁(yè)面跳轉(zhuǎn)
-(void)clickAction:(id)sender {
    DetailViewControllerOne *dVC = [[DetailViewControllerOne alloc] init];
    dVC.textString = self.textField.text;  //利用detail的textString屬性保存textField輸入的內(nèi)容
    [self.navigationController pushViewController:dVC animated:NO];
}

小結(jié):屬性傳值的核心就是在一個(gè)頁(yè)面通過使用另一個(gè)頁(yè)面的屬性驾孔,利用這個(gè)屬性來(lái)保存需要傳遞的信息芍秆,從而達(dá)到在另一個(gè)頁(yè)面能使用前一個(gè)頁(yè)面?zhèn)鬟f過來(lái)的信息。


(二)Block傳值
實(shí)踐方案:當(dāng)?shù)诙€(gè)頁(yè)面返回第一個(gè)頁(yè)面時(shí)翠勉,在第一個(gè)頁(yè)面中的lable顯示第二個(gè)界面textField中輸入的文本
實(shí)踐步驟:
首先我們建立一個(gè)RootViewControllers和一個(gè)DetailViewControllers(root頁(yè)面的label顯示detail頁(yè)面textField輸入的內(nèi)容)妖啥,在RootViewControllers里面新建一個(gè)用于顯示的Label

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

@interface RootViewControllerTwo : UIViewController

@property (nonatomic,retain) UILabel *label;

@end

在DetailViewControllers里面新建一個(gè)用于傳值的Block,一個(gè)Block方法和一個(gè)用于輸入內(nèi)容的textField

//DetailViewControllers.h

#import <UIKit/UIKit.h>

typedef void (^ReturnTextBlock)(NSString *showText);//重新定義了一個(gè)名字

@interface DetailViewControllerTwo :UIViewController

@property (nonatomic,retain) UITextField *tf;

@property (nonatomic,copy) ReturnTextBlock returnTextBlock;//定義的一個(gè)Block屬性

- (void)returnText:(ReturnTextBlock)block;

@end

將傳遞過來(lái)的block賦值給自己的屬性block对碌,然后找一個(gè)時(shí)機(jī)給block傳遞數(shù)據(jù)

//DetailViewControllers.m
#import "DetailViewControllerTwo.h"
#import "RootViewControllerTwo.h"

@implementation DetailViewControllerTwo

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //定義一個(gè)輸入框 將文字傳給第一個(gè)界面荆虱,并且顯示在前一個(gè)頁(yè)面的UILabel上
    self.tf = [[UITextField alloc]initWithFrame:CGRectMake(20,100,CGRectGetWidth(self.view.bounds) - 40 , 40)];
    self.tf.tintColor = [UIColor orangeColor]; 
    self.tf.backgroundColor = [UIColor greenColor];
    self.tf.placeholder = @"請(qǐng)輸入內(nèi)容";
    
    [self.view addSubview:self.tf];
    
    //定義一個(gè)按鈕
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20,300,CGRectGetWidth(self.view.bounds) - 40 , 40);
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
}

/*在第一個(gè)界面?zhèn)鬟M(jìn)來(lái)一個(gè)Block語(yǔ)句塊的函數(shù),把傳進(jìn)來(lái)的Block語(yǔ)句塊保存到本類的實(shí)例變
  量returnTextBlock(.h中定義的屬性)中朽们,然后尋找一個(gè)時(shí)機(jī)調(diào)用*/
-(void)returnText:(ReturnTextBlock)block{
    self.returnTextBlock = block;
}

//而這個(gè)時(shí)機(jī)就是當(dāng)視圖將要消失的時(shí)候怀读,需要重寫:
-(void)viewWillDisappear:(BOOL)animated{
    if (self.returnTextBlock !=nil) {
        self.returnTextBlock(self.tf.text);
    }
}

//此處的點(diǎn)擊事件也會(huì)觸發(fā)視圖消失,所以同樣會(huì)走上面的viewWillDisappear方法
-(void)clickAction:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}
@end

讀取block傳遞過來(lái)的數(shù)據(jù)骑脱,并顯示在label中

//RootViewControllers.m
#import "RootViewControllerTwo.h"
#import "DetailViewControllerTwo.h"

@interface RootViewControllerTwo ()

@end

@implementation RootViewControllerTwo

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Block傳值";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //定義一個(gè)按鈕
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20,300,CGRectGetWidth(self.view.bounds) - 40 , 40);
    button.backgroundColor = [UIColor blueColor];
    [button setTitle:@"下一頁(yè)" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    
    //定義一個(gè)顯示控件
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(20,100, CGRectGetWidth(self.view.bounds) - 40 , 40)];
    self.label.backgroundColor = [UIColor purpleColor];
    self.label.text = @"用于顯示從后面頁(yè)面返回的數(shù)據(jù)";//為了顯示第二個(gè)視圖控制器傳過來(lái)的字符串
    self.label.textColor = [UIColor whiteColor];
    [self.view addSubview:self.label];
}

-(void)clickAction:(id)sender{
    
    DetailViewControllerTwo * dVC =[[DetailViewControllerTwo alloc] init];//相對(duì)應(yīng)的將其實(shí)例化菜枷,否則找不到相應(yīng)的屬性
    
    //回調(diào)方法將輸入框中的數(shù)據(jù)傳輸過來(lái)
    [dVC returnText:^(NSString *showText) {
        self.label.text = showText;
    }];
    
    [self.navigationController pushViewController:dVC animated:YES];
}

小結(jié):其實(shí)block傳值還是有點(diǎn)類似于屬性傳值,但是他是將值保存在代碼塊中惜姐,通過關(guān)聯(lián)傳遞過來(lái)的代碼塊(頁(yè)面一)與自己的屬性代碼塊(頁(yè)面二)犁跪,以及使用代碼塊傳值(頁(yè)面二),回到頁(yè)面一中歹袁,頁(yè)面一回調(diào)代碼塊坷衍,以獲取代碼塊傳遞過來(lái)的值。


(三)代理傳值
實(shí)踐方案:第一個(gè)界面中的lable顯示第二個(gè)界面textField中輸入的文本
實(shí)踐步驟:
首先我們建立一個(gè)RootViewControllers和一個(gè)DetailViewControllers(root頁(yè)面的label顯示detail頁(yè)面textField輸入的內(nèi)容)条舔,首先我們先聲明一個(gè)代理以及代理需要實(shí)現(xiàn)的方法

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

@class DetailViewControllerThree;
@protocol PassingValueDeletegate <NSObject>

@optional
-(void)viewController:(DetailViewControllerThree *)viewController didPassingValueWithInfo:(id)info;

@end

@interface DetailViewControllerThree : UIViewController

@property(nonatomic, assign) id<PassingValueDeletegate> delegate;//通過代理傳值

@end

在一個(gè)需要傳值的時(shí)機(jī)枫耳,將需要傳遞的值保存到代理方法的參數(shù)中

//DetailViewController.m
#import "DetailViewControllerThree.h"

@interface DetailViewControllerThree ()
@property (nonatomic, strong) UITextField *textField;

@end

@implementation DetailViewControllerThree

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds)-40, 40);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blueColor];
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    [self.view addSubview:self.textField];
}

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

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSString *string;
    
    if ([_textField.text length] == 0) {
        string = @"用戶未輸入任何內(nèi)容";
    }else {
        string = _textField.text;
    }
    //視圖將要消失,通過代理傳值
    //首次判斷代理是否存在孟抗,并在代理能夠響應(yīng)代理方法時(shí)才執(zhí)行代理方法
    if (self.delegate && [self.delegate respondsToSelector:@selector(viewController:didPassingValueWithInfo:)]) {
        [self.delegate viewController:self didPassingValueWithInfo:string];
    }
}

-(UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, CGRectGetWidth(self.view.bounds) - 40, 40)];
    }
    _textField.placeholder = @"請(qǐng)輸入內(nèi)容";
    _textField.backgroundColor = [UIColor greenColor];

    return _textField;
}

-(void)clickAction:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

聲明RootViewController實(shí)現(xiàn)該代理迁杨,并實(shí)現(xiàn)該代理的方法钻心,而該代理方法就包含著傳遞過來(lái)的值

//RootViewController.m
#import "RootViewControllerThree.h"
#import "DetailViewControllerThree.h"

@interface RootViewControllerThree () <PassingValueDeletegate>

@property (nonatomic, strong) UILabel *showLabel;

@end

@implementation RootViewControllerThree
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"代理傳值";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.showLabel];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds)-40, 40);
    [button setTitle:@"下一頁(yè)" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:20];
    button.backgroundColor = [UIColor greenColor];
    
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

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

- (UILabel *)showLabel {
    if (!_showLabel) {
        _showLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, CGRectGetWidth(self.view.bounds)-40, 40)];
    }
    _showLabel.text = @"用于顯示后面頁(yè)面?zhèn)鬟^來(lái)的值";
    _showLabel.textColor = [UIColor whiteColor];
    _showLabel.backgroundColor = [UIColor purpleColor];
    return _showLabel;
}

-(void)clickAction:(id)sender {
    DetailViewControllerThree *dVC = [[DetailViewControllerThree alloc] init];

    dVC.delegate = self;
    
    [self.navigationController pushViewController:dVC animated:NO];
}

-(void)viewController:(DetailViewControllerThree *)viewController didPassingValueWithInfo:(id)info {
    _showLabel.text = info;  //代理方法傳遞過來(lái)的值
}

小結(jié):代理方法是用的比較多的,適用于任意界面之間傳值铅协,只需要聲明實(shí)現(xiàn)代理方法捷沸,就可以獲取傳遞過來(lái)的值


(四)單例傳值
實(shí)踐方案:第一個(gè)界面中的lable顯示第二個(gè)界面textField中輸入的文本,同時(shí)第二個(gè)界面中的lable顯示第一個(gè)界面textField中輸入的文本狐史,輸入文本互相傳遞
實(shí)踐步驟:新建一個(gè)單例

#import <Foundation/Foundation.h>

@interface AppStatus : NSObject {
    NSString *_contextStr;
}

@property(nonatomic,retain)NSString *contextStr;

+(AppStatus *)shareInstance;

@end

#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;
}

@end
#import "RootViewControllerFour.h"
#import "AppStatus.h"
#import "DetailViewControllerFour.h"

@interface RootViewControllerFour ()

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation RootViewControllerFour

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"單例傳值";
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds) -40, 40);
    [btn setTitle:@"Push" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor redColor];
    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [self.view addSubview:self.textField];
    self.label.frame = CGRectMake(20, 100, CGRectGetWidth(self.view.bounds) -40, 40);
    
    self.label.backgroundColor = [UIColor greenColor];
    [self.view addSubview:self.label];
}

-(void)viewWillAppear:(BOOL)animated {
    if ([AppStatus shareInstance].contextStr.length !=0) {
        self.label.text = [AppStatus shareInstance].contextStr;
    } else {
        self.label.text = @"用于現(xiàn)實(shí)后面頁(yè)面?zhèn)鬟f過來(lái)的值";
    }
}

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

-(UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 200, CGRectGetWidth(self.view.bounds)-40, 40)];
    }
    _textField.placeholder = @"請(qǐng)輸入內(nèi)容";
    _textField.backgroundColor = [UIColor purpleColor];
    _textField.textColor = [UIColor whiteColor];
    return _textField;
}

-(void)pushAction:(id)sender
{
//    _textField = (UITextField *)[self.view viewWithTag:1000];
    
    //單例傳值  將要傳遞的信息存入單例中(共享中)
    //  [[AppStatus shareInstance]setContextStr:tf.text]; 跟下面這種寫法是等價(jià)的
    [AppStatus shareInstance].contextStr = _textField.text;
    //導(dǎo)航push到下一個(gè)頁(yè)面
    //pushViewController 入棧引用計(jì)數(shù)+1痒给,且控制權(quán)歸系統(tǒng)
    DetailViewControllerFour *detailViewController = [[DetailViewControllerFour alloc]init];
    
    //導(dǎo)航push到下一個(gè)頁(yè)面
    [self.navigationController pushViewController:detailViewController animated:YES];
    
}

#pragma mark - Getter & Setter
LabelGetter(label, NSTextAlignmentCenter, ColorFromRGB(0xffffff), [UIFont systemFontOfSize:15])
#import "DetailViewControllerFour.h"
#import "AppStatus.h"

@interface DetailViewControllerFour ()

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation DetailViewControllerFour

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.label.frame = CGRectMake(20, 100, CGRectGetWidth(self.view.bounds) -40, 40);
    self.label.backgroundColor = [UIColor greenColor];
    [self.view addSubview:self.label];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 200, CGRectGetWidth(self.view.bounds) -40, 40)];
    self.textField.placeholder = @"請(qǐng)輸入內(nèi)容";
    self.textField.backgroundColor = [UIColor purpleColor];
    self.textField.textColor = [UIColor whiteColor];
    [self.view addSubview:self.textField];
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds) -40, 40);
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"發(fā)送" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
}

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

-(void)viewWillAppear:(BOOL)animated {
    if ([AppStatus shareInstance].contextStr.length !=0) {
        self.label.text = [AppStatus shareInstance].contextStr;
    } else {
        self.label.text = @"用于現(xiàn)實(shí)前面頁(yè)面?zhèn)鬟f過來(lái)的值";
    }
}

//pop回前一個(gè)頁(yè)面
-(void)doneAction:(id)sender {
    //單例傳值
    [AppStatus shareInstance].contextStr = _textField.text;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Getter & Setter
LabelGetter(label, NSTextAlignmentCenter, ColorFromRGB(0xffffff), [UIFont systemFontOfSize:15])

(五)通知傳值
實(shí)踐方案:第一個(gè)界面中的lable顯示第二個(gè)界面textField中輸入的文本
實(shí)踐步驟:
首先我們建立一個(gè)RootViewControllers和一個(gè)DetailViewControllers(root頁(yè)面的label顯示detail頁(yè)面textField輸入的內(nèi)容),首先我們RootViewController里面注冊(cè)一個(gè)通知監(jiān)聽骏全,并在頁(yè)面消失時(shí)移除該通知(注冊(cè)與移除需要對(duì)應(yīng))

#import "RootViewControllerFive.h"
#import "DetailViewControllerFive.h"

#define xbyNotification @"labelChange"

@interface RootViewControllerFive ()

@property (nonatomic, strong) UILabel *label;

@end

@implementation RootViewControllerFive

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    self.title = @"通知傳值";
    
    [self.view addSubview:self.label];
    
    UIButton *button  = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds)-40, 40);
    [button setTitle:@"點(diǎn)擊" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor blueColor];
    [self.view addSubview:button];
}

-(void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(labelTextChange:) name:xbyNotification object:nil];
}

//一開始準(zhǔn)備在這移除消息通知苍柏,結(jié)果GG了,啥通知都收不到
//-(void)viewWillDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
//放在這就好了
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(UILabel *)label {
    if (!_label) {
        _label = [[UILabel alloc ] initWithFrame:CGRectMake(20, 100, CGRectGetWidth(self.view.bounds)-40, 40)];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.backgroundColor = [UIColor purpleColor];
        _label.text = @"等待接收通知消息";
        _label.textColor = [UIColor whiteColor];
    }
    
    return _label;
}

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

-(void)clickAction:(id)sender {
    [self.navigationController pushViewController:[DetailViewControllerFive new] animated:NO];
}

-(void)labelTextChange:(NSNotification *)sender {
    NSDictionary *dic = sender.userInfo;
    self.label.text = dic[@"info"];
//    NSLog(@"收到通知");
}

點(diǎn)擊按鈕時(shí)發(fā)送通知

#import "DetailViewControllerFive.h"

#define xbyNotification @"labelChange"

@interface DetailViewControllerFive ()

@property (nonatomic, strong) UITextField *textField;

@end

@implementation DetailViewControllerFive

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.textField];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 300, CGRectGetWidth(self.view.bounds)-40, 40);
    [button setTitle:@"發(fā)送通知" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
}

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

-(UITextField *)textField {
    
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, CGRectGetWidth(self.view.bounds) - 40, 40)];
    }
    _textField.placeholder = @"請(qǐng)輸入內(nèi)容";
    _textField.backgroundColor = [UIColor greenColor];
    
    return _textField;
}

-(void)clickAction:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:xbyNotification object:self userInfo:@{@"info":_textField.text}];
    [self.navigationController popViewControllerAnimated:NO];
}

小結(jié):注冊(cè)通知與移除通知需要一一對(duì)應(yīng)姜贡,同時(shí)通知名稱要相同试吁,才能收到該通知發(fā)送的消息。


Demo下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者

  • 序言:七十年代末楼咳,一起剝皮案震驚了整個(gè)濱河市熄捍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌爬橡,老刑警劉巖治唤,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異糙申,居然都是意外死亡宾添,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門柜裸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)缕陕,“玉大人,你說我怎么就攤上這事疙挺】敢兀” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵铐然,是天一觀的道長(zhǎng)蔬崩。 經(jīng)常有香客問我,道長(zhǎng)搀暑,這世上最難降的妖魔是什么沥阳? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮自点,結(jié)果婚禮上桐罕,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好功炮,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布溅潜。 她就那樣靜靜地躺著,像睡著了一般薪伏。 火紅的嫁衣襯著肌膚如雪滚澜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天嫁怀,我揣著相機(jī)與錄音博秫,去河邊找鬼。 笑死眶掌,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的巴碗。 我是一名探鬼主播朴爬,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼橡淆!你這毒婦竟也來(lái)了召噩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤逸爵,失蹤者是張志新(化名)和其女友劉穎具滴,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體师倔,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡构韵,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了趋艘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疲恢。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖瓷胧,靈堂內(nèi)的尸體忽然破棺而出显拳,到底是詐尸還是另有隱情,我是刑警寧澤搓萧,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布杂数,位于F島的核電站,受9級(jí)特大地震影響瘸洛,放射性物質(zhì)發(fā)生泄漏揍移。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一货矮、第九天 我趴在偏房一處隱蔽的房頂上張望羊精。 院中可真熱鬧,春花似錦、人聲如沸喧锦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)燃少。三九已至束亏,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間阵具,已是汗流浹背碍遍。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留阳液,地道東北人怕敬。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像帘皿,于是被迫代替她去往敵國(guó)和親东跪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容