如何在SwiftUI中编程滚动列表?

44
在当前工具/系统中,比如刚发布的Xcode 11.4/iOS 13.4,似乎没有SwiftUI原生支持"scroll-to"功能在List中。所以即使他们,苹果公司,在下一个主要版本中提供了它,我仍然需要向后支持iOS 13.x。
那么我应该用最简单、最轻量的方式来实现呢? - 滚动列表到末尾 - 滚动列表到顶部 - 其他
(我不喜欢将完整的UITableView基础设施包装成UIViewRepresentable / UIViewControllerRepresentable,这是之前在SO上提出的建议)。

如果使用.frame(height: x)将高度设置为大于可滚动区域的值(其中x是大于内容高度的值),则表单或列表将无法滚动。 - Alex Brown
11个回答

0

两个部分:

  1. 使用 ScrollViewReader 包装 List(或 ScrollView
  2. 使用来自 ScrollViewReaderscrollViewProxy 滚动到 List 中元素的 id。你似乎可以使用 EmptyView()

下面的示例仅使用通知进行简单演示(如果可能,请改用函数!)。

ScrollViewReader { scrollViewProxy in
  List {
    EmptyView().id("top")  
  }
  .onReceive(NotificationCenter.default.publisher(for: .ScrollToTop)) { _ in
    // when using an anchor of `.top`, it failed to go all the way to the top
    // so here we add an extra -50 so it goes to the top
    scrollViewProxy.scrollTo("top", anchor: UnitPoint(x: 0, y: -50))
  }
}

extension Notification.Name {
  static let ScrollToTop = Notification.Name("ScrollToTop")
}

NotificationCenter.default.post(name: .ScrollToTop, object: nil)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接