Swiftui 返回多个选项的形状
所以我想的是,是否有一种方法可以创建一个Swiftui 返回多个选项的形状,swiftui,Swiftui,所以我想的是,是否有一种方法可以创建一个形状,在初始化时可以返回调用者想要的任何选项之一。例如: struct LetterTemplates: Shape { init(letterTemplate: LetterTemplate) { // This is where I'm confused. Can I somehow select which path to return based on some input by the caller??
形状
,在初始化时可以返回调用者想要的任何选项之一。例如:
struct LetterTemplates: Shape {
init(letterTemplate: LetterTemplate) {
// This is where I'm confused. Can I somehow select which path to return based on some input by the caller??
}
func path(in rect: CGRect) -> Path { ... } // Short Letter Template
func path(in rect: CGRect) -> Path { ... } // Long Letter Template
}
你直接问的是这个问题。要在使用闭包的语言中完成此操作,当需要将闭包转发给方法时,可以这样做(使用真实的实现,而不是fatalError()中的
):
struct-LetterTemplates:形状{
初始化(letterTemplate:letterTemplate){
开关字母模板{
案例。您可以尝试这样处理问题:使用可能的模板定义枚举:
enum LetterTemplate {
case short
case long
}
然后使用该枚举初始化LetterTemplateShape的实例,并使用它选择要在路径(in:)
中绘制的正确路径:
结构LetterTemplateShape:形状{
let letterTemplate: LetterTemplate
init(letterTemplate: LetterTemplate) {
self.letterTemplate = letterTemplate
}
func path(in rect: CGRect) -> Path {
switch letterTemplate {
case .short:
return ShortLetterTemplateShape().path(in: rect)
case .long:
return LongLetterTemplateShape().path(in: rect)
}
}
}
然后将枚举的每种情况的实际路径声明为单独的形状:
struct ShortLetterTemplateShape: Shape {
func path(in rect: CGRect) -> Path {
// actual implementation
}
}
struct LongLetterTemplateShape: Shape {
func path(in rect: CGRect) -> Path {
// actual implementation
}
}
为什么不能将letterTemplate
存储在本地属性中,然后在path(在…
func中)中使用?我可以向名为method的系统添加一个参数吗?类似于func path(在rect:CGRect中,模板:letterTemplate)的参数->Path
然后在模板上进行切换
?这也是您所说的策略模式,但也是OOP语言中的一种方式。切换可以提前移动并执行一次。最后一段代码是Apple的代码如何完成任务。他们只是不关心其他部分s、 在这两种情况下都会执行一次切换,不同之处在于我的实现只保留值类型,而不向等式添加引用类型。