gpt4 book ai didi

swiftui - 如何对不同的形状使用相同的修饰符集

转载 作者:行者123 更新时间:2023-12-04 14:45:04 26 4
gpt4 key购买 nike

作为我学习 SwiftUI 项目的一部分,我做了一些形状旋转,下面有代码。我想知道如何避免每个形状使用相同的三行修饰符。

func getShape(shape: Int, i: Int) -> AnyView {

switch shape {
case 0:
return AnyView(Rectangle()
.stroke(colors[Int(shapeColor)])
.frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
.rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
case 1:
return AnyView(Capsule()
.stroke(colors[Int(shapeColor)])
.frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
.rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
case 2:
return AnyView(Ellipse()
.stroke(colors[Int(shapeColor)])
.frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
.rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
default:
return AnyView(Rectangle()
.stroke(colors[Int(shapeColor)])
.frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
.rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))

}
}

最佳答案

使用助手AnyShape类型橡皮擦

struct AnyShape: Shape {
private let builder: (CGRect) -> Path

init<S: Shape>(_ shape: S) {
builder = { rect in
let path = shape.path(in: rect)
return path
}
}

func path(in rect: CGRect) -> Path {
return builder(rect)
}
}

你的函数可以写成

func getShape(shape: Int, i: Int) -> some View {
let selectedShape: AnyShape = {
switch shape {
case 0:
return AnyShape(Rectangle())
case 1:
return AnyShape(Capsule())
case 2:
return AnyShape(Ellipse())
default:
return AnyShape(Rectangle())
}
}()
return selectedShape
.stroke(colors[Int(shapeColor)])
.frame(width: CGFloat(shapeWidth), height: CGFloat(shapeHeight))
.rotationEffect(Angle(degrees: Double(i) * Double(angleStep))))
}

关于swiftui - 如何对不同的形状使用相同的修饰符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62602166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com