首页 > 解决方案 > NSLayoutManager 在 NSTextView 中为 mousePosition 返回不正确的 glyphIndex

问题描述

我有一个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 方向的偏移量大于左侧面板的宽度。

我在这里遗漏了什么,上面的代码有错误吗?

标签: swiftmacosnstextviewmousedownnslayoutmanager

解决方案


根据上面@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)in mouseMovedlocalMousePosition是视图的属性)。改变它以localMousePosition = convert(event.locationInWindow, from: nil)使一切正常。再次感谢@Willeke 指出这一点。


推荐阅读