![](/img/trans.png)
[英]How to set up an NSTextView programmatically with explicit NSLayoutManager, NSTextStorage, NSTextContainer?
[英]NSLayoutManager returns incorrect glyphIndex for mousePosition in NSTextView
我有一個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) }
似乎可以工作。
問題是我也在mouseMoved
中使用了localMousePosition = convert(event.locationInWindow, to: nil)
( localMousePosition
是視圖的屬性)。 將其更改為localMousePosition = convert(event.locationInWindow, from: nil)
使其全部正常工作。 再次感謝@Willeke指出這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.