📦AnyShape
SwiftUI ⟩ shapes ⟩ Shape ⟩ AnyShape
A type-erased shape value. You can use this type to dynamically switch between shape types.
struct MyClippedView: View {
var isCircular: Bool
var body: some View {
ClippedView()
// ✅ OK (將 Circle 與 Capsule 化為 AnyShape)
.clipShape(isCircular ? AnyShape(Circle()) : AnyShape(Capsule()))
ErrorView()
// 🐞 mismatching types (Circle, Capsule 為不同類型)
.clipShape(isCircular ? Circle() : Capsule())
}
}官方有 AnyShape 這個型別,估計實作方式可能類似下面:
import SwiftUI
struct MyAnyShape: Shape {
private var wrappedShape: any Shape
init<S: Shape>(_ wrapped: S) {
self.wrappedShape = wrapped // ⭐️ 直接儲存 Shape 實例
}
// ⭐️ Shape requirement
func path(in rect: CGRect) -> Path {
wrappedShape.path(in: rect)
}
}👉 參考: has non-Sendable type 👉 應用: view.clipShape()
Last updated
Was this helpful?