macOS按钮NSButton
macOS按钮NSButton

macOS按钮NSButton

NSButton 是 macOS AppKit 框架中的按钮组件类,用于在界面中实现点击操作(如提交、确认、切换等)。

基本用法

简单写法:

let button = NSButton(title: "点击我", target: self, action: #selector(buttonClicked))

完整写法:

let button = NSButton(frame: NSRect(x: 50, y: 50, width: 100, height: 40))
button.title = "点我"
button.target = self
button.action = #selector(buttonClicked)

在Storyboard / XIB 拖拽(在 Interface Builder 中),可以直接拖动按钮并连接IBAction。

常用属性

1、title:按钮上显示的文字。

button.title = "保存"

2、image:按钮图标(左侧)。

button.image = NSImage(systemSymbolName: "square.and.arrow.down", accessibilityDescription: nil)

3、bezelStyle:外观样式,如 .rounded, .texturedRounded 等。

常见样式:.rounded、.texturedRounded、.recessed、.shadowlessSquare和.inline。

4、state:当前状态(主要用于开关类按钮)。

5、isEnabled:是否启用。

6、target / action:设置点击事件回调。

button.target = self
button.action = #selector(buttonClicked)

7、keyEquivalent:设置快捷键触发。

使用示例

1、图文按钮

let button = NSButton()
button.title = "保存"
button.image = NSImage(systemSymbolName: "square.and.arrow.down", accessibilityDescription: nil)
button.imagePosition = .imageLeading

2、在SwiftUI中显示NSButton

struct ContentView: View {
    var body: some View {
        VStack {
            NSSomeView()
                .frame(width: 100,height:35)
        }
        .frame(width: 400,height:300)
    }
}

struct NSSomeView: NSViewRepresentable {
    func makeNSView(context: Context) -> NSButton {
        let button = NSButton(title: "点击我", target: SomeButton.shared, action: #selector(SomeButton.clickButton))
        button.image = NSImage(systemSymbolName: "square.and.arrow.down", accessibilityDescription: nil)
        button.imagePosition = .imageLeading
        return button
    }

    func updateNSView(_ nsView: NSButton, context: Context) {
        // 更新 NSView 时会调用,例如绑定颜色状态
    }
    
    class SomeButton {
        static var shared = SomeButton()
        @objc func clickButton() {
            print("按钮被点击!")
        }
    }
}

不同类型按钮

1、普通按钮:默认 .momentaryPushIn。

2、切换按钮:button.setButtonType(.toggle)。

3、单选按钮:button.setButtonType(.radio)。

4、多选按钮:button.setButtonType(.switch)。

但我在SwiftUI中使用NSViewRepresentable显示NSButton,实际上并不能修改按钮类型:

let button = NSButton(frame: NSRect(x: 0, y: 0, width: 100, height: 30))
button.title = "点击我"
button.setButtonType(.toggle) // 关键,设置为切换按钮
button.target = SomeButton.shared
button.action = #selector(SomeButton.clickButton)

按钮仍然是普通按钮,可能还需要配置其他属性。

总结

NSButton 是 macOS 原生的按钮控件,可以实现文字、图标、点击事件、切换状态、快捷键等,是构建 AppKit UI 的核心组件之一。

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注