UIKit UIButton.ButtonType.close 有 SwiftUI 版本吗?

问题描述 投票:0回答:4

现在,我正在从 UIKit 转换为 SwiftUI。在 UIKit 中,有一个原生的 Close, X-Styled Button -

UIButton.ButtonType.close,
,如下所示:

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

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

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

ios swift button swiftui uikit
4个回答
6
投票

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

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

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

Xcode 13.4 / iOS 15.5


5
投票

您可以使用

UIButton
嵌入 UIKit
UIViewRepresentable

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()
        }
    }
}

然后

CloseButton {
    // dismiss()
}

示例:

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

4
投票

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

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

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

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

我个人建议使用

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


3
投票

您可以使用

xmark.circle.fill
符号作为系统镜像:

XMARK

⚠️注意:

xmark.circle.fill
x.circle.fill

之间有区别
© www.soinside.com 2019 - 2024. All rights reserved.