概要
本文主要介紹如何通過NSNotification來實(shí)現(xiàn)兩個container view之間的數(shù)據(jù)的交互忠售。
步驟
1夷家、新建項(xiàng)目,打開storyboard,拖拽兩個container view至默認(rèn)的view controller中自娩。
image.png
2、分別為兩個Container View中添加Button和Label渠退,并且設(shè)置Auto-Label忙迁。(不會的同學(xué)請參考第一篇文章)
image.png
3、創(chuàng)建兩個NSViewController的子類MagicButtonViewController和BalanceViewController
image.png
4.為Container View中的這兩個View Controller添加Custom Class碎乃。
image.png
image.png
5.拖拽大法姊扔,將button拖拽至MagicButtonViewController.m中,將label拖拽至BalanceViewController.h中梅誓。
//MagicButtonViewController.m
- (IBAction)btn_magic:(id)sender {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"click" object:self ];
}
//BalanceViewController.h
#import <Cocoa/Cocoa.h>
@interface BalanceViewController : NSViewController
@property (weak) IBOutlet NSTextField *label_balance;
@end
//BalanceViewController.m
#import "BalanceViewController.h"
@interface BalanceViewController ()
@property NSInteger balance; //余額
@end
@implementation BalanceViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do view setup here.
_balance = 0; //初始化為0
//監(jiān)聽恰梢、執(zhí)行g(shù)etCash方法
NSNotificationCenter *nf = [NSNotificationCenter defaultCenter];
[nf addObserver:self selector:@selector(getCash:) name:@"click" object:nil];
}
//getCash方法
- (void)getCash:(NSNotification*)notification{
++_balance;
_label_balance.stringValue = [NSString stringWithFormat:@"余額:%ld元",_balance];
}
@end
6.完成佛南,效果如下。
image.png