在SwiftUI视图中两次引用同一路径的最佳方式是什么?

在SwiftUI视图中两次引用同一路径的最佳方式是什么?,swift,swiftui,swift5,Swift,Swiftui,Swift5,我试图创建一个动态生成的按钮,它使用相同的路径来绘制主形状,然后绘制边框。完整代码如下 我当前的最佳方法调用按钮生成器两次,但由于它使用随机数据(设计约束),连续调用使用不同的数据,因此边框不能正确重叠按钮形状。见下图 以下是如何做到这一点 备选案文1: struct MyButton: View { var color: String var title: String var height: Int var body: some View {

我试图创建一个动态生成的按钮,它使用相同的路径来绘制主形状,然后绘制边框。完整代码如下

我当前的最佳方法调用按钮生成器两次,但由于它使用随机数据(设计约束),连续调用使用不同的数据,因此边框不能正确重叠按钮形状。见下图


以下是如何做到这一点

备选案文1:

struct MyButton: View {
    var color: String
    var title: String
    var height: Int

    var body: some View {
        let path = ButtonPath().path(height: height)
        return VStack {
            ZStack {
                path.fill(Color(color))
                path.stroke(Color.white, lineWidth: 4).shadow(color: Color("gray4"), radius: 4, x: -10, y: -10)
                Text(self.title).font(.custom("Chaloops-Bold", size: 30)).tracking(5).shadow(radius: 2)
            }
            .foregroundColor(Color.white)
            .frame(height:130)
        }
    }
}
备选案文2:

struct MyButton: View {
    var color: String
    var title: String
    var height: Int

    private let path: Path

    init(color: String, title: String, height: Int) {
        self.color = color
        self.title = title
        self.height = height
        self.path = ButtonPath().path(height: height)
    }

    var body: some View {
        VStack {
            ZStack {
                path.fill(Color(color))
                path.stroke(Color.white, lineWidth: 4).shadow(color: Color("gray4"), radius: 4, x: -10, y: -10)
                Text(self.title).font(.custom("Chaloops-Bold", size: 30)).tracking(5).shadow(radius: 2)
            }
            .foregroundColor(Color.white)
            .frame(height:130)
        }
    }
}

非常感谢Asperi!我从你的两个变种中学到了很多,我能够移除我丑陋的黑客。
struct MyButton: View {
    var color: String
    var title: String
    var height: Int

    private let path: Path

    init(color: String, title: String, height: Int) {
        self.color = color
        self.title = title
        self.height = height
        self.path = ButtonPath().path(height: height)
    }

    var body: some View {
        VStack {
            ZStack {
                path.fill(Color(color))
                path.stroke(Color.white, lineWidth: 4).shadow(color: Color("gray4"), radius: 4, x: -10, y: -10)
                Text(self.title).font(.custom("Chaloops-Bold", size: 30)).tracking(5).shadow(radius: 2)
            }
            .foregroundColor(Color.white)
            .frame(height:130)
        }
    }
}