代码之家  ›  专栏  ›  技术社区  ›  swiftPunk Alexander

如何在扩展中推断泛型参数?

  •  0
  • swiftPunk Alexander  · 技术社区  · 4 年前

    我有一个非常简单的 自定义视图 它需要一个视图并对其进行修改!就像这段代码:

    struct CustomView<ViewType: View>: View {
        
        let content: () -> ViewType
        
        var body: some View {
            
            return content()
                .foregroundColor(.red)
            
        }
        
    }
    

    到现在为止,一直都还不错!

    现在我想做一个 自定义修改器 除此之外,就像这样:

    extension View {
    
        func customModifier<ViewModifierType: View>(viewModifier: () -> ViewModifierType) -> some View {
    
            // how can I import self from here?
            
            return viewModifier()
            
        }
    
    }
    

    用例:

    struct ContentView: View {
        
        var body: some View {
            
    
            Text("Hello, World!")
                .customModifier(viewModifier: { CustomView(content: { Text("Hello, World!") } ) }) // <<: Here is the issue!
    
            // How can I satisfy CustomView with self in extension? that could help to cut Text("Hello, World!") to feeding as content for CustomView?
            
        }
        
    }
    

    所以如果看到代码,我想做的就是切断 Text("Hello, World!") 使用扩展中的self并尝试使用这种形式的编码:

    .customModifier(viewModifier: { CustomView() })
    

    PS:我知道有这样的形式 CustomView() 我必须尊重泛型参数 CustomView 与单词 where 但我不知道该怎么把这些拼图拼在一起!

    0 回复  |  直到 4 年前
        1
  •  1
  •   Muzzle    4 年前

    如果我没理解错的话,试试这个

    extension View {
        func customModifier<ViewModifierType: View>(viewModifier: (Self) -> ViewModifierType) -> some View {
            return viewModifier(self)
        }
    }
    
        2
  •  0
  •   Leo Dabus    4 年前

    不确定你的目标是什么,但如果你只想在视图中添加一个红色前景,你需要实现一个视图修改器:

    struct RedForeground: ViewModifier {
        func body(content: Content) -> some View {
            content.foregroundColor(.red)
        }
    }
    

    然后使用修饰符方法调用它:

    Text("Text")
        .modifier(RedForeground())
    

    如果你想进一步简化它,你可以扩展 View 并添加使其成为计算属性:

    extension View {
        var redForeground: some View { modifier(RedForeground()) }
    }
    

    用法:

    Text("Text")
        .redForeground
    
        3
  •  0
  •   Phil Dukhov    4 年前

    你不能只是初始化 CustomView 没有视野,但你可以通过 自定义视图 初始化器作为函数 customModifier ,就像这样:

    struct ContentView: View {
        var body: some View {
            Text("Hello, World!")
                .customModifier(viewModifier: CustomView.init)
        }
    }
    
    struct CustomView<ViewType: View>: View {
        
        let content: ViewType
        
        var body: some View {
            return content
                .foregroundColor(.red)
        }
        
    }
    
    extension View {
        func customModifier<ViewModifierType: View>(viewModifier: (Self) -> ViewModifierType) -> some View {
            return viewModifier(self)
        }
    }