【问题标题】:Type 'any View' cannot conform to 'View' when using Gesture via function通过函数使用手势时,键入“任何视图”不能符合“视图”
【发布时间】:2022-07-23 00:39:30
【问题描述】:

我正在尝试将我的手势提取到一个函数中,以便在我的一个 Swift 包中使用。我遇到的问题是,当我尝试在我的一个视图上使用它时,它不再符合 View。

以下代码产生此错误:Type 'any View' cannot conform to 'View'

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Placeholder")
        } 
        .gesture(swipeDownGesture())
    }

    func swipeDownGesture() -> any Gesture {
        DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ gesture in
            if gesture.translation.height > 0 {
                // Run some code
            }
        })
    }
}

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    改用some

    func swipeDownGesture() -> some Gesture {   // << here !!
        DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ gesture in
            if gesture.translation.height > 0 {
                // Run some code
            }
        })
    }
    

    【讨论】:

      【解决方案2】:

      关键字someany 之间存在很大差异。 some 正在返回任何类型的 Gesture,它不会像 DragGesture 那样改变,它应该总是这样。而 any 返回的 Gesture 类型并不总是设置为 DragGesture 手势。

      在你的情况下,用 some 替换 any 就可以了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多