3

我正在 macOS 上使用 Swift 编写应用程序。我想创建一个带有垂直 NSStackView 的 NSAlert,让用户从 N 个选项中选择一个。为此,我将我的 NSStackView 连接到我的 NSAlert 的附件视图属性中,并且由于某种原因我的单选按钮不显示。

这是我到目前为止所尝试的:

let a = NSAlert()
a.messageText = "Dummy1"
a.informativeText = "Dummy2"
a.addButton(withTitle: "OK")

let rb = NSButton(radioButtonWithTitle: "Foo", target: nil, action: nil)
a.accessoryView = rb

a.runModal()

这向我显示了我的 NSAlert,其中有一个标记为 Foo 的单选按钮。所以附件视图似乎工作。

现在我将单选按钮放在 StackView 中:

let a = NSAlert()
a.messageText = "Dummy1"
a.informativeText = "Dummy2"
a.addButton(withTitle: "OK")

let rb = NSButton(radioButtonWithTitle: "Foo", target: nil, action: nil)
let vsv = NSStackView()
vsv.orientation = NSUserInterfaceLayoutOrientation.vertical
vsv.distribution = NSStackViewDistribution.equalSpacing
vsv.alignment = .leading
vsv.isHidden = false
vsv.addView(rb, in: .center)

a.accessoryView = vsv

a.runModal()

现在单选按钮不再出现。在 StackView 中添加更多单选按钮也无济于事。

4

1 回答 1

1

我能够让它工作,但我没有设置任何约束,因为我只需要一个固定的大小。这是一个堆叠两个具有固定宽度的文本字段的示例:

func makeAccessoryView(usernameField: NSTextField, passwordField: NSTextField) -> NSView {
    let stackView = NSStackView(views: [usernameField, passwordField])
    let width = 300
    let height = usernameField.frame.height + stackView.spacing + passwordField.frame.height
    stackView.setFrameSize(NSSize(width: width, height: height))
    stackView.translatesAutoresizingMaskIntoConstraints = true
    stackView.orientation = .vertical
    return stackView
}

// somewhere else...
let usernameField = NSTextField(...)
let passwordField = NSTextField(...)
alert.accessoryView = makeAccessoryView(usernameField: usernameField, passwordField: passwordField)
于 2020-01-29T02:06:07.680 回答