SwiftUI报错:'background(_:)'要求String遵循ShapeStyle(Xcode14 beta3)
问题解决:Instance method 'background(_:ignoresSafeAreaEdges:)' requires that 'String' conform to 'ShapeStyle'
错误原因
你直接将字符串"StickyButtonBackground"传给了.background()方法,但SwiftUI的.background(_:)需要接收符合ShapeStyle协议的类型(比如Color、ImagePaint、渐变等),字符串本身不满足该协议要求,因此触发报错。
解决方案
根据StickyButtonBackground在Assets中的资源类型,选择对应修改方式:
情况1:它是颜色资源
将第40行的代码:
.background("StickyButtonBackground")
替换为:
.background(Color("StickyButtonBackground"))
情况2:它是图片资源
如果想用图片作为按钮背景,可修改为:
.background(Image("StickyButtonBackground").resizable().scaledToFill())
或者使用ImagePaint适配背景显示:
.background(ImagePaint(image: Image("StickyButtonBackground")))
修改后的完整代码示例
import SwiftUI struct ContentView: View { var body: some View { ScrollView { Text("text") .font(.title2) .fontWeight(.heavy) .foregroundColor(Color.black) .multilineTextAlignment(.center) .padding([.top, .leading, .trailing], 15.0) Image("Customise") .resizable() .scaledToFit() Text("xkdlvlx") .font(.title2) .fontWeight(.heavy) .foregroundColor(Color.black) .multilineTextAlignment(.center) .padding([.top, .leading, .trailing], 15.0) Image("Customise") .resizable() .scaledToFit() } .safeAreaInset(edge: .bottom) { Button("Hello"){ } .frame(maxWidth: .infinity) .padding(.vertical) // 这里替换为对应修改后的代码,示例为颜色资源情况 .background(Color("StickyButtonBackground")) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } }
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

