SwiftUI自定义Button在tvOS显示异常 多平台复用样式不一致如何解决
问题原因
tvOS 平台的 Button 自带默认平台专属样式,会自动给内容添加左右内边距、焦点/按压态的装饰容器,你的代码中把背景、圆角等自定义修饰符加在了 Button 视图本身的外层,默认样式自带的额外边距没有被自定义背景覆盖,就会出现你看到的首尾多余块。
另外你没有显式关闭 Button 的默认平台样式,自定义样式会和 tvOS 默认的卡片式按钮样式叠加,也会导致显示异常。
解决方法
- 给
Button显式添加.buttonStyle(.plain)修饰符,关闭 tvOS 自带的默认按钮样式,消除默认添加的内边距和装饰容器。 - 建议将背景、圆角、内边距等样式修饰符挪到
Button内容闭包的外层,而非Button本身的外层,避免不同平台对Button视图的默认行为干扰自定义样式。
修改后的核心代码参考:
var body: some View { Button(action: tapEvent) { HStack { if let image = icon, let uiimage = UIImage(named: image) { Image(uiImage: uiimage) .resizable() .renderingMode(.template) .foregroundColor(iconColorForState(active: active, buttonMode: mode)) .frame(width: 20, height: 20, alignment: .center) } if let title = label { Text(title) .lineLimit(1) } } // 把样式相关修饰符挪到内容层 .foregroundColor(foregroundColorForState(active: active, buttonMode: mode)) .padding() .background(self.focused ? focussedBackgroundColorFor(active: active, mode: mode) : backgroundColorFor(active: active, mode: mode)) .cornerRadius(8) } // 关闭默认按钮样式 .buttonStyle(.plain) .disabled(disabled) .frame(height: heightForButtonSize(size: size ?? .Base)) .modifier(FocusableModifier { focused in self.focused = focused }) }
内容的提问来源于stack exchange,提问作者Steven B.
相关产品推荐
相关产品推荐

