Ios UITextView行距导致段落行之间的光标高度不同

Ios UITextView行距导致段落行之间的光标高度不同,ios,objective-c,swift,Ios,Objective C,Swift,我在UITextview中使用NSMutableParagraphStyle在每行文本之间添加行距 当我在textview中键入内容时,光标高度是正常的。但是,当我将光标位置移动到第二行(不是最后一行)的文本时,光标的高度越来越大 我应该怎么做才能使每行文本中的光标高度正常? 这是我目前正在使用的代码: NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle

我在
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}];

最后我找到了解决我问题的办法

可以通过子类化
UITextView
,然后重写
caretRectForPosition:position
函数来更改光标高度。例如:

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


更新:Swift 2.x或Swift 3.x 看


更新:Swift 4.x 对于Swift 4.x,请使用
caretRect(对于位置:UITextPosition)->CGRect

import UIKit

class MyTextView: UITextView {

    override func caretRect(for position: UITextPosition) -> CGRect {
        var superRect = super.caretRect(for: position)
        guard let font = self.font else { return superRect }

        // "descender" is expressed as a negative value, 
        // so to add its height you must subtract its value
        superRect.size.height = font.pointSize - font.descender 
        return superRect
    }
}
文档链接:

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


这是一种记录在案的方法吗?(编辑:是的,它在
UITextView
符合()的
UITextView
协议中。当选择此文本时,句柄非常大,知道如何修复它吗?Swift 4将
caretRectForPosition(位置:UITextPosition)
更改为:
caretRect(位置:UITextPosition)
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
    }
}