代码之家  ›  专栏  ›  技术社区  ›  John Rudy

在Cocoa中以编程方式创建控件

  •  15
  • John Rudy  · 技术社区  · 17 年前

    MacOSX的Cocoa编程,第3版 ,在第245页(第17章),您通常会在Interface Builder中创建视图。但是,可以在代码中创建它们,la:

    NSView *superview = [window contentView]; 
    NSRect frame = NSMakeRect(10, 10, 200, 100); 
    NSButton *button = [[NSButton alloc] initWithFrame:frame]; 
    [button setTitle:@"Click me!"]; 
    [superview addSubview:button]; 
    [button release]; 
    

    3 回复  |  直到 17 年前
        1
  •  25
  •   Fenhl Atiar Talukdar    11 年前

    您可以使用一个简单的赋值将它们连接起来。要继续上面的代码,请执行以下操作:

    [button setTarget: self];
    [button setAction: @selector(myButtonWasHit:)];
    
        2
  •  11
  •   Mike Abdullah    17 年前

    如果您想以第一响应者而不是特定对象为目标:

    [button setTarget:nil];
    [button setAction:@selector(myAction:)];
    
        3
  •  2
  •   User    11 年前

    斯威夫特:

    button.target = self
    button.action = "myAction:"
    

    当然,在self中添加myAction函数:

    func myAction(sender: NSButton) {
        println("click!")
    }