Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

ios - Longpress and list scrolling

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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{}
      }
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...