有条件地创建形状 - SwiftUI
Conditional creation of Shapes - SwiftUI
我正在尝试编写一个根据指定条件创建形状的函数,但出现编译错误。
func createShape() -> some Shape {
switch self.card.shape {
case .oval:
return Capsule()
case .rectangle:
return Rectangle()
case .circe:
return Circle()
default:
return Circle()
}
}
我遇到的错误:
函数声明了一个不透明的 return 类型,但其主体中的 return 语句没有匹配的基础类型
来自 Asperi 的评论和 link:
更改为:
@ViewBuilder
func createShape() -> some View {
switch self.card.shape {
case .oval:
Capsule()
case .rectangle:
Rectangle()
case .circle:
Circle()
default:
Circle()
}
}
在这个post的帮助下,对我有帮助的是:
创建 AnyShape
:
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AnyShape: Shape {
public var make: (CGRect, inout Path) -> ()
public init(_ make: @escaping (CGRect, inout Path) -> ()) {
self.make = make
}
public init<S: Shape>(_ shape: S) {
self.make = { rect, path in
path = shape.path(in: rect)
}
}
public func path(in rect: CGRect) -> Path {
return Path { [make] in make(rect, &[=10=]) }
}
}
#endif
然后:
func createShape() -> AnyShape {
switch self.card.shape {
case .oval:
return AnyShape(Capsule())
case .rectangle:
return AnyShape(Rectangle())
case .circe:
return AnyShape(Circle())
}
}
我正在尝试编写一个根据指定条件创建形状的函数,但出现编译错误。
func createShape() -> some Shape {
switch self.card.shape {
case .oval:
return Capsule()
case .rectangle:
return Rectangle()
case .circe:
return Circle()
default:
return Circle()
}
}
我遇到的错误:
函数声明了一个不透明的 return 类型,但其主体中的 return 语句没有匹配的基础类型
来自 Asperi 的评论和 link:
更改为:
@ViewBuilder
func createShape() -> some View {
switch self.card.shape {
case .oval:
Capsule()
case .rectangle:
Rectangle()
case .circle:
Circle()
default:
Circle()
}
}
在这个post的帮助下,对我有帮助的是:
创建 AnyShape
:
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AnyShape: Shape {
public var make: (CGRect, inout Path) -> ()
public init(_ make: @escaping (CGRect, inout Path) -> ()) {
self.make = make
}
public init<S: Shape>(_ shape: S) {
self.make = { rect, path in
path = shape.path(in: rect)
}
}
public func path(in rect: CGRect) -> Path {
return Path { [make] in make(rect, &[=10=]) }
}
}
#endif
然后:
func createShape() -> AnyShape {
switch self.card.shape {
case .oval:
return AnyShape(Capsule())
case .rectangle:
return AnyShape(Rectangle())
case .circe:
return AnyShape(Circle())
}
}