SwiftUI:使用.borderless按钮样式时标签出现异常边框问题
macOS SwiftUI:Sheet打开的DetailView中Borderless按钮异常显示边框的解决方法
问题描述
开发macOS应用时,实现了两种打开DetailView的方式:
- 点击"Hello"通过Sheet展示DetailView
- 点击"World"通过NavigationLink展示DetailView
DetailView内的按钮设置了.buttonStyle(.borderless),但只有Sheet打开的情况下,按钮图标周围会出现边框,NavigationLink打开则完全正常。
环境信息
- Xcode 15 beta 4
- macOS 13.4.1
复现代码
import SwiftUI struct ContentView: View { @State private var showingDetail = false var body: some View { NavigationStack { Text("Hello") .frame(width: 100, height: 100) .onTapGesture { showingDetail = true } .sheet(isPresented: $showingDetail) { DetailView() .frame(width: 300, height: 300) } NavigationLink { DetailView() .frame(width: 300, height: 300) } label: { Text("World") } } } } struct DetailView: View { var body: some View { Button() { print("Button Clicked") } label: { Image(systemName: "globe") .resizable() .frame(width: 200, height: 200) .foregroundColor(Color(.blue)) } .buttonStyle(.borderless) } }
解决方案
这是Xcode 15 beta版本的SwiftUI适配bug,以下几种方法可临时修复:
方法1:强制取消按钮边框圆角
在.buttonStyle(.borderless)后追加.buttonBorderShape(.roundedRectangle(radius: 0)),强制覆盖默认的焦点边框样式:
Button() { print("Button Clicked") } label: { Image(systemName: "globe") .resizable() .frame(width: 200, height: 200) .foregroundColor(Color(.blue)) } .buttonStyle(.borderless) .buttonBorderShape(.roundedRectangle(radius: 0))
方法2:替换为PlainButtonStyle
将.buttonStyle(.borderless)替换为.buttonStyle(PlainButtonStyle()),该样式在Sheet场景下的表现更稳定:
Button() { print("Button Clicked") } label: { Image(systemName: "globe") .resizable() .frame(width: 200, height: 200) .foregroundColor(Color(.blue)) } .buttonStyle(PlainButtonStyle())
方法3:取消Sheet内视图的默认焦点
Sheet打开时会自动给可交互元素添加焦点边框,给DetailView添加.focusable(false)可以禁用该行为:
.sheet(isPresented: $showingDetail) { DetailView() .frame(width: 300, height: 300) .focusable(false) }
方法4:升级到正式版Xcode
beta版本的UI细节问题通常会在正式版中修复,后续可关注Xcode更新,升级后验证问题是否自然消失。
内容的提问来源于stack exchange,提问作者ykay
相关产品推荐
相关产品推荐

