SwiftUI是否内置UIKit的UIButton.ButtonType.close等效按钮?若无如何实现?
SwiftUI实现UIKit风格关闭按钮方案
SwiftUI目前没有内置与UIKit中UIButton.ButtonType.close完全一致的关闭按钮组件,不过可以通过以下两种方式实现匹配原生风格且适配明暗模式的关闭按钮:
方法一:复用UIKit原生按钮(推荐)
通过UIViewRepresentable直接包装UIKit的原生关闭按钮,自动继承系统的明暗模式适配和交互样式:
struct CloseButton: UIViewRepresentable { var action: () -> Void func makeUIView(context: Context) -> UIButton { let button = UIButton(type: .close) button.addTarget(context.coordinator, action: #selector(Coordinator.tapped), for: .touchUpInside) return button } func updateUIView(_ uiView: UIButton, context: Context) {} func makeCoordinator() -> Coordinator { Coordinator(action: action) } class Coordinator: NSObject { var action: () -> Void init(action: @escaping () -> Void) { self.action = action } @objc func tapped() { action() } } } // 使用示例 struct ContentView: View { var body: some View { CloseButton { // 点击后的逻辑 print("关闭按钮触发") } } }
方法二:纯SwiftUI自定义实现
如果偏好纯SwiftUI方案,可以利用系统动态颜色自定义按钮,自动适配明暗模式:
struct CustomCloseButton: View { var action: () -> Void // 系统动态颜色,自动适配明暗模式 private let iconColor = Color(UIColor.label) private let bgColor = Color(UIColor.systemGray5) var body: some View { Button(action: action) { Image(systemName: "xmark") .foregroundColor(iconColor) .frame(width: 30, height: 30) .background(bgColor) .clipShape(Circle()) .contentShape(Circle()) // 确保点击区域为圆形 } } } // 使用示例 struct ContentView: View { var body: some View { CustomCloseButton { // 点击后的逻辑 print("自定义关闭按钮触发") } } }
如果需要贴近Apple Maps中的按钮样式,可调整背景色透明度:
.background(bgColor.opacity(0.8))
内容的提问来源于stack exchange,提问作者Awesomeplayer165
相关产品推荐
相关产品推荐

