使用形状叠加时,SwiftUI 错误类型“() -> ()”无法符合“ShapeStyle”

DrG*_*zoX 2 swiftui

为什么我在此代码中收到错误“Type '() -> ()' 无法符合 'ShapeStyle'”?它在其他地方也有效。

RoundedRectangle(cornerRadius: globals.cornerRadius).fill(Color.gray).overlay{
          Spacer()
          Text("Some text")
              .font(Font.custom("OpenSans-Regular", size: 17))
              .foregroundColor(.white)
              .multilineTextAlignment(.leading)
}.frame(width: .infinity, height: 100)
Run Code Online (Sandbox Code Playgroud)

rob*_*off 5

我推断您的部署目标是 iOS 13 或 iOS 14(或早于 iOS 15 的其他版本)。

\n

您的使用.overlay { ... }需要修饰符的重载overlay这是在 iOS 15 中引入的。

\n

由于您的部署目标是早于 iOS 15 的版本,因此编译器会尝试使用此重载.overlay,但此重载要求覆盖内容符合ShapeStyle. (iOS 15 中也引入了这种重载。为什么 Swift 更喜欢它?我不知道!但它是唯一对该错误消息有意义的重载。)

\n

您真正想要的是的重载.overlay,它允许覆盖内容为 any View,但不接受函数参数。所以改成.overlay{ ... }\ .overlay( ... )xe2\x80\x94,也就是把大括号改成圆括号。您还需要介绍一个VStack或其他容器视图。因此:

\n
RoundedRectangle(cornerRadius: globals.cornerRadius).fill(Color.gray).overlay(\n    VStack {\n          Spacer()\n          Text("Some text")\n              .font(Font.custom("OpenSans-Regular", size: 17))\n              .foregroundColor(.white)\n              .multilineTextAlignment(.leading)\n    }\n).frame(width: .infinity, height: 100)\n
Run Code Online (Sandbox Code Playgroud)\n