【问题标题】:NSLayoutManager returns incorrect glyphIndex for mousePosition in NSTextViewNSLayoutManager 在 NSTextView 中为 mousePosition 返回不正确的 glyphIndex
【发布时间】:2019-07-03 17:50:39
【问题描述】:

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

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

【问题讨论】:

  • 使用convert(_:from:) 代替convert(_:to:)?检查localMousePosition的值。
  • 这确实有效,谢谢,甚至不知道from: 存在。有趣/令人困惑的是,为什么我需要在另一个面板折叠时使用 to: 而如果不是,则使用 from:
  • 使用to:nil 将视图转换为窗口。使用from:nil 从窗口转换为视图。如果您必须使用to:nil 从窗口转换为视图,那么某处存在错误。
  • 啊,我也在其他地方使用to: nil(在mouseMoved)。将其更改为 from: nil 解决了问题。

标签: swift macos nstextview mousedown nslayoutmanager


【解决方案1】:

根据上面@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)
}

似乎有效。

问题是我在mouseMoved 中也使用了localMousePosition = convert(event.locationInWindow, to: nil)localMousePosition 是视图的属性)。将其更改为localMousePosition = convert(event.locationInWindow, from: nil) 使一切正常。再次感谢@Willeke 指出这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多