SwiftUI on Mac - How do I designate a button as being the primary?

前端 未结 3 455
暖寄归人
暖寄归人 2021-01-02 11:44

In AppKit I would do this by assigning its key equivalent to be ↩ or making its cell the window\'s default. However, neither of these seems possible in SwiftUI, so h

3条回答
  •  醉梦人生
    2021-01-02 12:22

    Here is a shorter, but less generic solution to create a primary button with return key equivalent, and default button blue tinting.

    struct PrimaryButtonView: NSViewRepresentable {
        typealias NSViewType = PrimaryButton
    
        let title: String
        let action: () -> Void
    
        init(_ title: String, action: @escaping () -> Void) {
            self.title = title
            self.action = action
        }
    
        func makeNSView(context: Context) -> PrimaryButton {
            PrimaryButton(title, action: action)
        }
    
        func updateNSView(_ nsView: PrimaryButton, context: Context) {
            return
        }
    }
    
    
    class PrimaryButton: NSButton {
        let buttonAction: () -> Void
    
        init(_ title: String, action: @escaping () -> Void) {
            self.buttonAction = action
            super.init(frame: .zero)
            self.title = title
            self.action = #selector(clickButton(_:))
            bezelStyle = .rounded  //Only this style results in blue tint for button
            isBordered = true
            focusRingType = .none
            keyEquivalent = "\r"
        }
    
        required init?(coder: NSCoder) {
            fatalError()
        }
    
        @objc func clickButton(_ sender: PrimaryButton) {
            buttonAction()
        }
    }
    

提交回复
热议问题