问题
Using SwiftUI (latest XCode and testing on IOS 13.3) I'm trying to implement a long press gesture on items in a list, to allow user interaction with the individual items. The problem is that when I set "onLongPressGesture" anywhere in the list (on items, on the list itself), the list cannot be scrolled anymore. I can easily get a simple tap to work but a long press blocks scrolling.
I've put together a small example that show this issue:
struct ContentView: View
{
let data = [
"Test 1","Test 2","Test 3","Test 4","Test 5",
"Test 6","Test 7","Test 8","Test 9","Test 10",
"Test 11","Test 12","Test 13","Test 14","Test 15",
"Test 16","Test 17","Test 18","Test 19","Test 20"
]
var body: some View
{
List
{
ForEach(data,id:\.self)
{
item in
Text(item).onLongPressGesture{}
}
}
}
}
If I try to drag the list pressing on any text, the list wont move. If I remove the longpress handler, it moves no matter where I press down.
回答1:
I asked this on the Apple Developer Forum as well and got a solution for the problem. If the view defines an onTapGesture handler before onLongPressGesture, the list will be scrollable while supporting long press on the individual items.
The onTapGesture handler can be empty as long as it is declared first.
struct ContentView: View
{
let data = [
"Test 1","Test 2","Test 3","Test 4","Test 5",
"Test 6","Test 7","Test 8","Test 9","Test 10",
"Test 11","Test 12","Test 13","Test 14","Test 15",
"Test 16","Test 17","Test 18","Test 19","Test 20"
]
var body: some View
{
List
{
ForEach(data,id:\.self)
{
item in
Text(item).onTapGesture{}.onLongPressGesture{}
}
}
}
}
回答2:
I think you should dig around composing with combining gestures. Here you can see, how to compose two and more gestures, but in your case I think you need exclusive behavior (which is described in this article). So you can combine DragGesture
and LongPressGesture
but for ScrollView
(I didn't found any solution for scrolling List
). Here are example 1 and example 2 of how to control ScrollView.content.offset
(for scrolling on DragGesture
).
来源:https://stackoverflow.com/questions/59440283/longpress-and-list-scrolling