NSLayoutManager为NSTextView中的mousePosition返回不正确的glyphIndex [英] NSLayoutManager returns incorrect glyphIndex for mousePosition in NSTextView
问题描述
我有一个NSTextView
子类作为NSSplitViewController
中的右侧项目,左侧面板是NSOutlineView
.要在文本视图中按下命令键时处理鼠标单击,我添加了以下内容以查找鼠标下方的字形:
I have an NSTextView
subclass as the right item in an NSSplitViewController
, the left panel is an NSOutlineView
. To process mouse clicks while the command key is pressed in the text view, I added the following to find the glyph that is under the mouse:
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左右,从而选择了错误的字形.我的文本视图只有等宽字符,因此偏移量不是由其他字形引起的.
However, this results in an index that is about 10 or so too high, thus selecting the wrong glyph. My text view has only monospaced characters, so the offset is not caused by additional glyphs.
有趣的是,如果我折叠左侧面板(在代码或情节提要中),则会得到正确的索引.但是在x方向上的偏移量大于左侧面板的宽度.
Interestingly, if I collapse the left panel (in code or in the storyboard), I get the correct index. But the offset in the x direction is more than the width of the left panel.
我在这里缺少什么,上面的代码有错误吗?
What am I missing here, is there an error in the code above?
推荐答案
基于上面@Willeke的评论,我对代码进行了以下更改:
Based on the comment by @Willeke above, I made the following change to my code:
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)
}
似乎可以正常工作.
Seems to work.
问题是我也在mouseMoved
中也使用了localMousePosition = convert(event.locationInWindow, to: nil)
(localMousePosition
是视图的属性).将其更改为localMousePosition = convert(event.locationInWindow, from: nil)
使其全部起作用.再次感谢@Willeke指出这一点.
The problem was that I was using localMousePosition = convert(event.locationInWindow, to: nil)
in mouseMoved
as well (localMousePosition
is a property of the view). Changing that to localMousePosition = convert(event.locationInWindow, from: nil)
made it all work. Thanks again to @Willeke for pointing this out.
这篇关于NSLayoutManager为NSTextView中的mousePosition返回不正确的glyphIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!