UITextView lineSpacing使光标高度不同

nov*_*ung 23 objective-c ios swift

我正在使用NSMutableParagraphStyleUITextview在每行文本之间添加行间距.

当我在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}];
Run Code Online (Sandbox Code Playgroud)

nov*_*ung 28

最后,我得到了解决我问题的解决方案.

通过继承UITextView,然后覆盖caretRectForPosition:position函数,可以更改光标高度.例如:

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

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


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

内特的回答.


更新:Swift 4.x

对于Swift 4.x使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这是一个记录的方法吗?(编辑:是的,它在'UITextInput`协议中,`UITextView`符合(https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITextInput_Protocol/index.html#//apple_ref/OCC/INTF/UITextInput). (2认同)

Nat*_*olz 10

对于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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Swift 4将`caretRectForPosition(position:UITextPosition)`更改为:`caretRect(for position:UITextPosition)` (2认同)