- 一步一步熟悉Mac app开发(九)之NSPopover
- 一步一步熟悉Mac app开发(四)之ArrayControll
- 一步一步熟悉Mac app开发(二)之NSCollectionV
- 一步一步熟悉Mac app开发(三)之NSTableView
- 一步一步熟悉Mac app开发(七)之NSAlert
- 一步一步熟悉Mac app开发(一)之containerView
- 一步一步熟悉Mac app开发(六)之NSOutlineView
- 一步一步熟悉Mac app开发(八)之NSNotificatio
- 一步一步熟悉Mac app开发(十一)之Radio Button
- 一步一步熟悉Mac app开发(十)之Cocoa Binding
概要
阶段一、再次实现简单的Popover Demo。
阶段二、熟悉NSNotificationCenter中UserInfo参数传递。
阶段一
1、新建工程,在默认的View Controller中加入一个按钮。

2、添加一个新的View Controller,并设置其大小为200*50。

3、设置其StoryBoard ID为“Popover”。

4、将“点击输入你的姓名”按钮,拖拽大法至ViewController.m内。


5、btn_input_name按钮的代码如下:
- (IBAction)btn_input_name:(id)sender {
NSViewController* vc = [[NSStoryboard storyboardWithName:@"Main" bundle:nil] instantiateControllerWithIdentifier:@"Popover"];
NSPopover *popover = [[NSPopover alloc] init];
popover.contentViewController = vc;
popover.behavior = NSPopoverBehaviorTransient; //自动关闭popover
[popover showRelativeToRect:_btn_input_name.bounds ofView:_btn_input_name preferredEdge:NSRectEdgeMaxY];
}
6、阶段一完成,效果如下。

阶段二
1、创建一个NSViewController的子类“PopoverViewController”,并且设置"Popover"的Custom Class为“PopoverViewController”。

2、拖拽大法,将“确认”按钮拖拽至PopoverViewController中。

3、添加代码。
- (IBAction)btn_click:(id)sender {
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
NSString *name = _text_name.stringValue;
[nc postNotificationName:@"click" object:self userInfo:@{@"name":name}];
}
4、在ViewController.m中添加代码。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(sayHi:) name:@"click" object:nil];
}
-(void) sayHi:(NSNotification *)nc{
NSAlert *alert = [[NSAlert alloc] init];
NSString*name = nc.userInfo[@"name"];
alert.messageText = @"系统提示:";
alert.informativeText = [NSString stringWithFormat:@"你好,%@!",name];
[alert addButtonWithTitle:@"你好"];
[alert runModal];
}
5、阶段二完成,效果如下。


网友评论