如何在macOS SwiftUI中创建大尺寸Accented高亮按钮
问题解决方法
你之前使用系统内置.bordered样式时出现布局异常,是因为该样式自带固定的内边距、圆角布局规则,直接给内容加padding或设置frame会和系统规则冲突,推荐通过自定义ButtonStyle完全控制按钮外观。
1. 基础目标按钮实现
// 自定义macOS边框按钮样式 struct LargeBorderedButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .padding(.horizontal, 32) .padding(.vertical, 12) .foregroundColor(.accentColor) .background( RoundedRectangle(cornerRadius: 8, style: .continuous) .stroke(Color.accentColor, lineWidth: 1.5) ) // 可选添加按压反馈效果 .opacity(configuration.isPressed ? 0.7 : 1) .scaleEffect(configuration.isPressed ? 0.98 : 1) } } // 调用方式 Button(action: { // 点击逻辑写在这里 }) { Text("Sign In") } .buttonStyle(LargeBorderedButtonStyle())
如果需要调整按钮尺寸,直接给configuration.label添加frame属性即可,不会出现布局错位问题。
2. Pages风格脉冲高亮效果实现
在自定义样式的基础上叠加脉冲动画层即可实现高亮效果:
// 带脉冲高亮的按钮样式 struct HighlightedBorderedButtonStyle: ButtonStyle { @State private var animateHighlight = false func makeBody(configuration: Configuration) -> some View { configuration.label .padding(.horizontal, 32) .padding(.vertical, 12) .foregroundColor(.accentColor) .background( RoundedRectangle(cornerRadius: 8, style: .continuous) .stroke(Color.accentColor, lineWidth: 1.5) ) // 脉冲高亮层 .overlay( RoundedRectangle(cornerRadius: 8, style: .continuous) .stroke(Color.accentColor, lineWidth: 2) .scaleEffect(animateHighlight ? 1.2 : 1) .opacity(animateHighlight ? 0 : 1) ) .opacity(configuration.isPressed ? 0.7 : 1) .scaleEffect(configuration.isPressed ? 0.98 : 1) .onAppear { // 启动循环动画,可自行调整时长、动画曲线 withAnimation(.easeOut(duration: 1.5).repeatForever(autoreverses: false)) { animateHighlight = true } } } }
如果不需要默认展示高亮,把animateHighlight状态变量移到父视图,按需触发即可。
内容的提问来源于stack exchange,提问作者Ben Myers
相关产品推荐
相关产品推荐

