代码之家  ›  专栏  ›  技术社区  ›  Duck

类型“()->N”不能符合“视图”

  •  1
  • Duck  · 技术社区  · 2 年前

    StackOverflow上有一些标题相同的问题,但它们与我所问的无关。

    我有一个按钮的高亮样式。

    struct HighlightableButtonStyle<N, H>: ButtonStyle where N: View, H: View {
      
      private let alignment: Alignment
      private let normal: () -> N
      private let highlighted: () -> H
      
      init(alignment: Alignment = .center, 
           @ViewBuilder normal: @escaping () -> N,
           @ViewBuilder highlighted: @escaping () -> H) {
        self.alignment = alignment
        self.normal = normal
        self.highlighted = highlighted
      }
      
      func makeBody(configuration: Configuration) -> some View {
        configuration.label
          .frame(maxWidth: .infinity, maxHeight: .infinity)
          .contentShape(Rectangle())
          .background(alignment: alignment, content: {
            configuration.isPressed ? Color.red : Color.blue //1
          })
      }
    }
    

    我的问题是用 //1

    如果行在is is,它编译得很好,但我想将颜色传递给样式,所以我将该行更改为

    configuration.isPressed ? highlighted : normal
    

    我得到了这个错误

    Result values in '? :' expression have mismatching types '() -> H' and '() -> N'
    Insert ' as! () -> N'
    Type '() -> N' cannot conform to 'View'
    

    最有趣的是最后一行。N怎么可能不符合观点呢?

    我错过了什么?

    1 回复  |  直到 2 年前
        1
  •  2
  •   Sweeper    2 年前

    highlighted normal 函数 。您应该调用它们(通过添加 () 最后),使他们产生 View

    if configuration.isPressed {
        highlighted()
    } else {
        normal()
    }
    

    请注意,此处不能使用三元运算符,因为 突出显示 典型的 返回不同类型- H N 分别地