swift - 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 方向的偏移量大于左侧面板的宽度。
我在这里遗漏了什么,上面的代码有错误吗?
解决方案
根据上面@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 mouseMoved
(localMousePosition
是视图的属性)。改变它以localMousePosition = convert(event.locationInWindow, from: nil)
使一切正常。再次感谢@Willeke 指出这一点。
推荐阅读
- javascript - 我试图在按钮移动时移动光标
- python - Vkonakte 的机器人不回复消息
- c# - C# 将对象转换为不安全的 void*
- html - 如何使图像连续
- keras - Keras 层的稀疏输出
- django - 是否可以通过 Django 中的反向模型分配 OneToOneField?
- .net-core - 使用 dotnet publish 命令发布时无法排除 web.config 文件
- firebase - 在没有互联网连接的情况下使用 Firebase 模拟器
- python - 如何保持websocket打开
- python - 创建 pyLDAvis 的 ZipFile