我有一个NSTextView
子类作为在NSSplitViewController
权项,左边的面板是NSOutlineView
。要处理的鼠标点击,而命令键在文本视图中压,我增加了以下内容,你字形是鼠标下:
override func mouseDown(with event: NSEvent) {
guard
let lm = self.layoutManager,
let tc = self.textContainer
else { return }
let localMousePosition = convert(event.locationInWindow, to: nil)
var partial = CGFloat(1.0)
let glyphIndex = lm.glyphIndex(for: localMousePosition, in: tc, fractionOfDistanceThroughGlyph: &partial)
print(glyphIndex)
}
然而,这导致了为约10左右的过高,因此选择错误的字形的索引。我的文字图只有等宽字符,因此偏移不会造成额外的字形。
有趣的是,如果我崩溃左侧面板(代码或在故事板),我得到了正确的索引。但在x方向偏移大于左侧面板的宽度。
缺少什么我在这里,有没有在上面的代码中的错误?
基于以上通过的@Willeke评论,我做了如下改变我的代码:
localMousePosition = convert(event.locationInWindow, from: nil)
if enclosingScrollView?.frame.width == window?.frame.width {
// left panel is collapsed, so use convert: to:
localMousePosition = convert(event.locationInWindow, to: nil)
}
似乎工作。
的问题是,我是在使用localMousePosition = convert(event.locationInWindow, to: nil)
mouseMoved
以及(localMousePosition
是视图的一个属性)。改变这种以localMousePosition = convert(event.locationInWindow, from: nil)
使得它所有的工作。再次感谢@Willeke指出这一点。