UITextView lineSpacing make cursor height different between paragraph lines

后端 未结 2 805
Happy的楠姐
Happy的楠姐 2020-12-03 01:27

I\'m using NSMutableParagraphStyle in my UITextview for adding linespace between each row text.

When I type something in textview, cursor h

2条回答
  •  执笔经年
    2020-12-03 01:49

    Finally I found a solution that solved 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

    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

提交回复
热议问题