.scrollDisabled(true)
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()
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