UITextView lineSpacing causes different cursor height inbetween paragraph lines

Finally I found a solution that solve my problem.

Changing the cursor height is possible by subclassing the UITextView, then overriding the caretRectForPosition:position function. For example:

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

Documentation link: https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrectforposition


Update: Swift 2.x or Swift 3.x

See Nate’s answer.


Update: Swift 4.x or Swift 5.x

For Swift 4.x use caretRect(for position: 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
    }
}

Documentation link: https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrect

Leave a Comment