UITextView lineSpacing cause different cursor height between paragraph lines UITextView lineSpacing cause different cursor height between paragraph lines ios ios

UITextView lineSpacing cause different cursor height between 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 UIKitclass 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


And for Swift 2.x or Swift 3.x:

import UIKitclass 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    }}


matomo