UITextView lineSpacing使光标高度不同

时间:2013-11-26 03:28:04

标签: ios objective-c swift

我在NSMutableParagraphStyle中使用UITextview在每行文字之间添加行间距。

当我在textview中输入内容时,光标高度正常。但是当我将光标位置移动到第二行(而不是最后一行)上的文本时,光标高度变得越来越大。

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 个答案:

答案 0 :(得分:27)

最后,我找到了解决问题的解决方案。

通过继承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 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

答案 1 :(得分: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
    }
}