簡體   English   中英

修復 UITextView 中修改段落間距的 cursor 大小

[英]Fix cursor size for modified paragraph spacing in UITextView

我有一個自定義的、可編輯的 UITextView,我修改了段落間距,如下所示:

func layoutManager(_ layoutManager: NSLayoutManager, paragraphSpacingBeforeGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
    return 10
}

func layoutManager(_ layoutManager: NSLayoutManager, paragraphSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
    return 10
}

這導致 cursor 非常大。 我試圖通過覆蓋caretRect來解決這個問題:

override func caretRect(for position: UITextPosition) -> CGRect {
    let defaulCaretRect = super.caretRect(for: position)
    return CGRect(x: defaulCaretRect.origin.x, y: defaulCaretRect.origin.y, width: defaulCaretRect.width, height: 22)
}

它在某些情況下完美運行,但在其他情況下, origin.y是錯誤的:

錯誤的來源.y

如果我調整origin.y ,它會在正確的情況下破壞它。 我不知道如何識別origin.y需要修復。 我錯過了什么嗎?

我在這里看到了一些使用以下內容的舊答案:

rect.size.height = font.pointSize - font.descender

但是由於某種原因,這沒有效果。 有任何想法嗎?

最后,較大的段落間距也會導致選擇句柄過大:

在此處輸入圖像描述

還有什么辦法解決嗎?

我想我已經想通了。 正如在 SO 上找到的其他問題中所建議的那樣,使用字體調整插入符號的高度似乎效果很好。 缺少的是修復插入符號的原點 Y。

我認為 Apple 給我們UITextPosition一定是有原因的。 使用它,我能夠獲得行文本和段落文本。 有了這些,我可以檢查插入符號是否在導致問題的段落的第一行。

override func caretRect(for position: UITextPosition) -> CGRect {
    var superRect = super.caretRect(for: position)
    
    guard let paragraphRange = tokenizer.rangeEnclosingPosition(position, with: .paragraph, inDirection: .storage(.backward)),
          let paragraphText = text(in: paragraphRange)else { return superRect }
    
    guard let lineRange = tokenizer.rangeEnclosingPosition(position, with: .line, inDirection: .storage(.backward)),
          let lineText = text(in: lineRange) else { return superRect }
    
    guard let font = font else { return superRect }
    
     if paragraphText.hasPrefix(lineText) {
        superRect.origin.y += 10
    }
    
    superRect.size.height = font.pointSize - font.descender
    
    return superRect
}

不過,我不知道如何修復大選擇句柄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM