iOS – UITextView lineSpacing使光标高度不一样

我在我的UITextview使用NSMutableParagraphStyle添加每行文本之间的行空间。

当我在textview中键入内容时,光标高度是正常的。 但是当我将光标位置移动到第二行(而不是最后一行)上的文本时,光标高度变得越来越大。

在这里输入图像说明

我应该怎么做才能使光标高度正常在文本的每一行? 这是我目前使用的代码:

 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 30.; textView.font = [UIFont fontWithName:@"Helvetica" size:16]; textView.attributedText = [[NSAttributedString alloc] initWithString:@"My Text" attributes:@{NSParagraphStyleAttributeName : paragraphStyle}]; 

最后我得到解决我的问题的解决scheme。

我们可以通过caretRectForPosition:position UITextView来改变游标高度,然后重写caretRectForPosition:position函数。 例如:

 - (CGRect)caretRectForPosition:(UITextPosition *)position { CGRect originalRect = [super caretRectForPosition:position]; originalRect.size.height = 18.0; return originalRect; } 

文档链接: https : //developer.apple.com/documentation/uikit/uitextinput/1614518-caretrectforposition

而对于Swift 2. x或Swift 3. x

 import UIKit class MyTextView : UITextView { override func caretRectForPosition(position: UITextPosition) -> CGRect { var superRect = super.caretRectForPosition(position) guard let isFont = self.font else { 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 return superRect } }