我一直在玩UITextView(Swift 4.2)中的归属文本,并注意到一旦我在设计中引入了 "paragraphSpacingBefore",Caret在每个新段落的第一行就变得太大了。
我在Stackoverflow上找到了这个建议的修复方法,似乎可以解决caret大小的问题。我发现的问题是,当目标行是一个新段落的开始时,caret本身就浮在目标行之上。
UITextView lineSpacing让光标高度不一样的问题
我试着解了一下,保持了原答案的核心思想,增加了一些偏移逻辑。在调试的过程中,我注意到原来的答案中的卡口大小总是在不需要的时候调整大小,所以我加了一个方差过滤器(只有当方差> 10%时才调整)。这样做是因为我认为每次调整都会干扰我对浮动尾数问题的解决。
如果有人能看看我提出的方法,提出改进建议或更好的方法等,我会很感激。
override func caretRect(for position: UITextPosition) -> CGRect {
var superRect = super.caretRect(for: position)
guard let isFont = self.font else {
return superRect
}
let proposedHeight: CGFloat = isFont.pointSize - isFont.descender
var delta: CGFloat = superRect.size.height - proposedHeight
delta = (delta * delta).squareRoot()
//If the delta is < 10% of the original height just return the original rect
if delta / superRect.size.height < 0.1 {
return superRect
}
superRect.size.height = isFont.pointSize - isFont.descender
// "descender" is expressed as a negative value,
// so to add its height you must subtract its value
superRect.origin.y = superRect.origin.y + delta
// delta is used to correct for resized caret floating above the target line
return superRect
}
我得到了一个解决方案。
// Fix long cursor height when at the end of paragraph with paragraphspacing and wrong cursor position in titles with paragraph spacing before
override public func caretRect(for position: UITextPosition) -> CGRect {
var superRect = super.caretRect(for: position)
guard let isFont = self.font else { return superRect }
let location = self.offset(from: self.beginningOfDocument, to: position)
if let paragrahStyle = self.storage.attribute(.paragraphStyle, at: location, effectiveRange: nil) as? NSParagraphStyle {
superRect.origin.y += paragrahStyle.paragraphSpacingBefore
}
superRect.size.height = isFont.pointSize - isFont.descender
return superRect
}
真正的问题 paragraphSpacingBefore
. 所以你要做的就是获取段落样式属性,获取间距,然后按这个间距移动光标。这对所有的文字都很有效。