UIKit UIButton.ButtonType.close 是否有 SwiftUI 版本?

Awe*_*165 4 button uikit ios swift swiftui

现在,我正在从 UIKit 转换为 SwiftUI。在 UIKit 中,有一个原生的关闭、X 样式按钮-UIButton.ButtonType.close,如下所示:

在此输入图像描述

我想在 SwiftUI 中找到与此等效的内容(如果已经内置于 SwiftUI 中)。如果苹果还没有开始构建/转换它,这是可以理解的。我在 Apple 地图应用程序中也看到了这一点,我相信它是用 SwiftUI 构建的,如下所示(在面板的右下角):

在此输入图像描述

如果没有内置的按钮样式,如何为这个关闭按钮创建一个适应浅色和深色模式的视图?太感谢了!

编辑:在 UIKIt 的故事板编辑器中,这是我正在寻找的内容:

在此输入图像描述

Asp*_*eri 6

SwiftUI 不使用“按钮类型”的概念,而是你可以自己构造它,例如

Button(action: {}) {
    Image(systemName: "xmark.circle.fill")   // << base !!
        .resizable()
        .frame(width: 32, height: 32) // << for demo
        .foregroundColor(.gray)
}
Run Code Online (Sandbox Code Playgroud)

*根据需要使用任何其他修饰符

演示

Xcode 13.4 / iOS 15.5


MMP*_*MP0 6

您可以嵌入 UIKitUIButtonUIViewRepresentable.

struct CloseButton: UIViewRepresentable {
    private let action: () -> Void
    
    init(action: @escaping () -> Void) {
        self.action = action
    }
    
    func makeUIView(context: Context) -> UIButton {
        let button = UIButton(type: .close)
        button.addTarget(context.coordinator, action: #selector(Coordinator.perform), for: .primaryActionTriggered)
        return button
    }
    
    func updateUIView(_ uiView: UIButton, context: Context) {
        context.coordinator.action = action
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(action: action)
    }
    
    class Coordinator {
        var action: () -> Void
        
        init(action: @escaping () -> Void) {
            self.action = action
        }
        
        @objc func perform() {
            action()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

进而

CloseButton {
    // dismiss()
}
Run Code Online (Sandbox Code Playgroud)

例子:

SomeView()
    .toolbar {
        ToolbarItem(placement: .navigationBarTrailing) {
            CloseButton {
                dismiss()
            }
            .disabled(isBusy) // SwiftUI modifiers work fine.
        }
    }
Run Code Online (Sandbox Code Playgroud)


Jor*_*n H 5

目前无法在 SwiftUI 中使用系统按钮类型(包括关闭按钮)。我\xe2\x80\x99已提交FB10380135来请求添加此内容。

\n

同时,您可以使按钮看起来像系统关闭按钮。Apple 设计传播者 Mike Stern 在 Ask Apple 问答中指出:

\n
\n

模态关闭按钮使用 15pt 粗体\n的“xmark”SF 符号(常规尺寸符号,不是大或小变体)和 30\xc3\x9730pt\n圆圈。命中区域可能更大,因为我们通常采用的目标大小至少为 44\xc3\x9744pt。

\n
\n

另请注意,关闭按钮不会随着动态类型大小的增加/减小而改变大小。请务必将其辅助功能标签设置为 \xe2\x80\x9cclose\xe2\x80\x9d 并添加对大型内容查看器的支持,以便使用辅助功能文本大小的用户可以点击并按住按钮以显示带有“关闭”字样的大 xmark 符号下。

\n

我个人建议使用UIViewRepresentable添加一个真正的关闭UIButton按钮,而不是尝试完全复制它 - 请参阅 MMP0 提供的答案。

\n