清单如果需要支持水平滚动的列表子视图,则不能垂直滚动 我有一个包含一些视图的列表,其中一些需要水平滚动。重要的是要注意,这些视图都不需要垂直滚动。当我的鼠标徘徊在视图上...

问题描述 投票:0回答:1
最小的可复制代码。

.scrollDisabled(true)

我希望列表无论如何都会接收垂直滚动事件。
    

通过指的是这篇文章和这篇文章,我得到了解决方法。

尽管我的问题已经解决,但我仍在等待本地的Swiftui解决方案。这只是解决方法。

1。首先,基于此帖子
,我需要实现自己的
import SwiftUI struct ContentView: View { var body: some View { List { ForEach(0..<5) { index in Text("\(index) line") } ScrollView(.horizontal) { Text("hello, world! hello, world! hello, world! hello, world! hello, world!\n hello, world! hello, world! hello, world! \n hello, world! hello, world! hello, world! hello, world!") }.font(.largeTitle) ForEach(5..<10) { index in Text("\(index) line") } } } } #Preview { ContentView() }

并覆盖

NSScrollView()
swift macos swiftui swiftui-list swiftui-scrollview
1个回答
0
投票
还通过覆盖

scrollWheel()来转发垂直滚动事件,但它“太敏感”了。用户的手指无法准确地滚动; Y轴上总是会产生一定的距离。因此,即使它似乎“不那么侵入性”,我也没有采用这种方法。 wantsForwardedScrollEvents() 2。我需要创建一个在Swiftui中使用它。

class MTHorizontalScrollView: NSScrollView { var currentScrollIsHorizontal = false override func scrollWheel(with event: NSEvent) { if event.phase == NSEvent.Phase.began || (event.phase == NSEvent.Phase.ended && event.momentumPhase == NSEvent.Phase.ended) { currentScrollIsHorizontal = abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) } if currentScrollIsHorizontal { super.scrollWheel(with: event) } else { self.nextResponder?.scrollWheel(with: event) } } }

3。也许完成步骤2足以使用,但是在这里我将其更进一步,并将其扩展到

NSViewRepresentable
,以便于任何地方更容易使用。
struct NSScrollViewWrapper<Content: View>: NSViewRepresentable { let content: Content init(@ViewBuilder content: () -> Content) { self.content = content() } func makeNSView(context: Context) -> NSScrollView { let scrollView = MTHorizontalScrollView() scrollView.hasHorizontalScroller = true scrollView.hasVerticalScroller = false scrollView.verticalScrollElasticity = .none scrollView.horizontalScrollElasticity = .allowed scrollView.autohidesScrollers = true scrollView.drawsBackground = false let hostingView = NSHostingView(rootView: content) hostingView.translatesAutoresizingMaskIntoConstraints = false scrollView.documentView = hostingView NSLayoutConstraint.activate([ hostingView.topAnchor.constraint(equalTo: scrollView.topAnchor), hostingView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), hostingView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), hostingView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor) ]) return scrollView } func updateNSView(_ nsView: NSScrollView, context: Context) { if let hostingView = nsView.documentView as? NSHostingView<Content> { hostingView.rootView = content } } } 4。一切都准备就绪,现在可以使用。
View
	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.