【问题标题】:Conditional creation of Shapes - SwiftUI形状的条件创建 - SwiftUI
【发布时间】:2021-05-16 13:07:46
【问题描述】:

我正在尝试编写一个根据指定条件创建形状但出现编译错误的函数。

func createShape() -> some Shape {
    switch self.card.shape {
    case .oval:
        return Capsule()
    case .rectangle:
        return Rectangle()
    case .circe:
        return Circle()
    default:
        return Circle()
    }
}

我得到的错误:

函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型

【问题讨论】:

标签: swiftui shapes


【解决方案1】:

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, &$0) }
    }
}

#endif

然后:

func createShape() -> AnyShape {
    switch self.card.shape {
    case .oval:
        return AnyShape(Capsule())
    case .rectangle:
        return AnyShape(Rectangle())
    case .circe:
        return AnyShape(Circle())
    }
}

【讨论】:

    【解决方案2】:

    来自Asperi的评论和链接:

    改为:

    @ViewBuilder
    func createShape() -> some View {
        switch self.card.shape {
        case .oval:
            Capsule()
        case .rectangle:
            Rectangle()
        case .circle:
            Circle()
        default:
            Circle()
        }
    }
    

    【讨论】:

    • 我需要函数createShape 专门返回一个形状
    猜你喜欢
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多