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

28

我在我的 UITextview 中使用 NSMutableParagraphStyle 来为每一行文字添加行间距。

当我在文本视图中输入文字时,光标的高度是正常的。但是当我将光标位置移动到第二行文字上(不是最后一行),光标的高度会变大。

big caret

我应该怎么做才能使每一行文字的光标高度都正常呢?这是我目前正在使用的代码:

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}];
2个回答

39

最终我找到了解决我的问题的方法。

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

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

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


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

请查看Nate的答案


更新:Swift 4.x 或 Swift 5.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
    }
}

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


2
这是一个有文档记录的方法吗?(编辑:是的,它在UITextInput协议中,而UITextView符合该协议(https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITextInput_Protocol/index.html#//apple_ref/occ/intf/UITextInput)。) - oztune
1
当选择这段文本时,手柄非常大,有什么办法可以修复吗? - Hugo Alonso

11

对于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
    }
}

2
Swift 4 将 caretRectForPosition(position:UITextPosition) 更改为:caretRect(for position: UITextPosition) - jeffjv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接