'SwiftUI Error Type '() -> ()' cannot conform to 'ShapeStyle' when using overlay with shape
Why do I get the error "Type '() -> ()' cannot conform to 'ShapeStyle'" in this code? It works in other places.
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)
Solution 1:[1]
I deduce that your deployment target is iOS 13 or iOS 14 (or something else older than iOS 15).
Your use of .overlay { ... } requires this overload of the overlay modifier, which was introduced in iOS 15.
Because your deployment target is something older than iOS 15, the compiler is trying to use this overload of .overlay instead, but this overload requires that the overlay content conform to ShapeStyle. (This overload was also introduced in iOS 15. Why would Swift prefer it? I don't know! But it's the only one that makes sense for that error message.)
What you really want is this overload of .overlay, which allows the overlay content to be any View, but doesn't take a function argument. So change .overlay{ ... } to .overlay( ... )—that is, change the braces to parentheses. You will also need to introduce a VStack or other container view. Thus:
RoundedRectangle(cornerRadius: globals.cornerRadius).fill(Color.gray).overlay(
VStack {
Spacer()
Text("Some text")
.font(Font.custom("OpenSans-Regular", size: 17))
.foregroundColor(.white)
.multilineTextAlignment(.leading)
}
).frame(width: .infinity, height: 100)
Solution 2:[2]
This is one of the many unclear error messages in XCode. Though XCode indicates a problem with fill(), the actual problem here seems to be the spacer() in the overlay. The reason is probably that overlay expects a view type. Spacer is not a view type. If you remove Spacer(), the error disappears.
RoundedRectangle(cornerRadius: globals.cornerRadius).fill(Color.gray).overlay{
Text("Some text")
.font(Font.custom("OpenSans-Regular", size: 17))
.foregroundColor(.white)
.multilineTextAlignment(.leading)
}.frame(width: .infinity, height: 100)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | DrGonzoX |
