【问题标题】:In Interface builder, how can I add a custom button to a window title bar?在界面生成器中,如何将自定义按钮添加到窗口标题栏?
【发布时间】:2012-11-20 14:55:27
【问题描述】:

在我的 OS X 应用程序中,使用 Interface Builder,我有一个如下所示的窗口:

我想在右侧添加一个按钮,以实现此目的:

如果可以,我该怎么做?

【问题讨论】:

  • 我猜我可能需要使用无边框窗口并自己绘制替换标题栏。

标签: cocoa interface-builder nspanel


【解决方案1】:

Interface Builder 无法做到这一点,但是您可以通过一点编码来完成它:

NSButton *closeButton = [window standardWindowButton:NSWindowCloseButton]; // Get the existing close button of the window. Check documentation for the other window buttons.
NSView *titleBarView = closeButton.superview; // Get the view that encloses that standard window buttons.
NSButton *myButton = …; // Create custom button to be added to the title bar.
myButton.frame = …; // Set the appropriate frame for your button. Use titleBarView.bounds to determine the bounding rect of the view that encloses the standard window buttons.
[titleBarView addSubview:myButton]; // Add the custom button to the title bar.

【讨论】:

    【解决方案2】:

    Swift 2.2 和自动布局,在标题栏右侧创建一个“确定”按钮:

    let myButton = NSButton()
    myButton.title = "OK"
    myButton.bezelStyle = .RoundedBezelStyle
    
    let titleBarView = window!.standardWindowButton(.CloseButton)!.superview!
    titleBarView.addSubview(myButton)
    myButton.translatesAutoresizingMaskIntoConstraints = false
    titleBarView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[myButton]-2-|", options: [], metrics: nil, views: ["myButton": myButton]))
    titleBarView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-1-[myButton]-3-|", options: [], metrics: nil, views: ["myButton": myButton]))
    

    使用自动布局,您无需对按钮的框架进行硬编码。即使您调整窗口大小,它也始终位于标题栏的右侧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-13
      • 2012-02-19
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 2010-09-11
      相关资源
      最近更新 更多