美文网首页码农的世界Mac OS XMac OS X 软件开发
一步一步熟悉Mac app开发(九)之NSPopover

一步一步熟悉Mac app开发(九)之NSPopover

作者: 拳战攻城师 | 来源:发表于2018-08-06 18:03 被阅读0次

    概要

    阶段一、再次实现简单的Popover Demo。
    阶段二、熟悉NSNotificationCenter中UserInfo参数传递。

    阶段一

    1、新建工程,在默认的View Controller中加入一个按钮。


    image.png

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


    image.png

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


    image.png

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


    image.png
    image.png

    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、阶段一完成,效果如下。


    image.png

    阶段二

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


    image.png

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


    image.png
    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、阶段二完成,效果如下。


    image.png image.png

    相关文章

      网友评论

        本文标题:一步一步熟悉Mac app开发(九)之NSPopover

        本文链接:https://www.haomeiwen.com/subject/snpyvftx.html