简体   繁体   English

NSLayoutManager为NSTextView中的mousePosition返回不正确的glyphIndex

[英]NSLayoutManager returns incorrect glyphIndex for mousePosition in NSTextView

I have an NSTextView subclass as the right item in an NSSplitViewController , the left panel is an NSOutlineView . 我有一个NSTextView的子类作为权项在NSSplitViewController ,左面板是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)
}

However, this results in an index that is about 10 or so too high, thus selecting the wrong glyph. 但是,这会导致索引大约为10左右太高,从而选择了错误的字形。 My text view has only monospaced characters, so the offset is not caused by additional glyphs. 我的文本视图只有等宽字符,因此偏移量不是由其他字形引起的。

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. 但是在x方向上的偏移量大于左侧面板的宽度。

What am I missing here, is there an error in the code above? 我在这里缺少什么,上面的代码有错误吗?

Based on the comment by @Willeke above, I made the following change to my code: 根据上面@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) } 

Seems to work. 似乎可以工作。

The problem was that I was using localMousePosition = convert(event.locationInWindow, to: nil) in mouseMoved as well ( localMousePosition is a property of the view). 问题是我也在mouseMoved中使用了localMousePosition = convert(event.locationInWindow, to: nil)localMousePosition是视图的属性)。 Changing that to localMousePosition = convert(event.locationInWindow, from: nil) made it all work. 将其更改为localMousePosition = convert(event.locationInWindow, from: nil)使其全部正常工作。 Thanks again to @Willeke for pointing this out. 再次感谢@Willeke指出这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM