我的 View 包含一个水平滚动的 ScrollView ,其中包含多个垂直滚动的 TableView 。
参见图表:
但是,当光标位于表格 View 上时,表格 View 会阻止 ScrollView 中的水平滚动。
如何让滚动传递到 super View ?
<小时/>应用代码
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var viewController: ViewController!
func applicationDidFinishLaunching(aNotification: NSNotification) {
viewController = ViewController(nibName: "ViewController", bundle: nil)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
window.contentView!.addSubview(viewController.view)
//...
}
//...
}
View Controller
class ViewController: NSViewController {
@IBOutlet weak var scrollView: NSScrollView!
//...
func addListView(listPath: String) {
let listView = ListViewController(nibName: "ListView", bundle: nil)
listView!.listPath = listPath
listView!.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentView.addSubview(listView!.view)
//...
}
//...
}
ListView
class ListViewController: NSViewController {
@IBOutlet weak var itemsTitleView: NSTextField!
@IBOutlet weak var itemsTableView: MyTableView!
//...
}
表格 View
class MyTableView: NSTableView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
var mainScrollView: NSScrollView? {
let app = NSApplication.sharedApplication()
let delegate = app.delegate as! AppDelegate
return delegate.viewController.scrollView
}
override func mouseDown(theEvent: NSEvent) {
// do nothing
}
override func scrollWheel(theEvent: NSEvent) {
if theEvent.scrollingDeltaY == 0 {
// It's a horizontal scroll -> redirect it
if let tableScrollView = enclosingScrollView, mainScrollView = mainScrollView {
mainScrollView.scrollWheel(theEvent)
}
} else {
// It's a vertical scroll -> behave normally
super.scrollWheel(theEvent)
}
}
}
最佳答案
我要尝试的第一件事是捕获滚动事件,因为它被传递到 TableView 。一旦确定事件对象代表水平滚动手势,请将其重定向到主 ScrollView 。
class MyTableView: NSTableView {
var mainScrollView: NSScrollView? {
// Your tables will need some way to access the main scroll view.
// I'm assuming here that there's a reference to it on the AppDelegate
let app = NSApplication.sharedApplication()
let delegate = app.delegate as! AppDelegate
return delegate.mainScrollView
}
override func scrollWheel(theEvent: NSEvent) {
if theEvent.scrollingDeltaY == 0 {
// It's a horizontal scroll -> redirect it
if let tableScrollView = enclosingScrollView, mainScrollView = self.mainScrollView {
mainScrollView.scrollWheel(theEvent)
}
} else {
// It's a vertical scroll -> behave normally
super.scrollWheel(theEvent)
}
}
}
但我不得不说,任何时候你开始搞乱这样的事件,你都需要为副作用做好准备;在我创建的用于测试此代码的简单演示应用程序中,它似乎工作正常,但如果此方法引发额外的挑战,请不要感到惊讶。
关于swift - 水平和垂直嵌套 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010533/