lineSpacing使光标高度不同

lineSpacing使光标高度不同

本文介绍了UITextView lineSpacing使光标高度不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UITextview中的NSMutableParagraphStyle在每个行文本之间添加行距.

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

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

When I type something in textview, cursor height is normal. but when I move cursor position to text on the 2nd row (not the last row), cursor height is getting bigger.

如何使文本的每一行中的光标高度正常? 这是我当前正在使用的代码:

What should I do to make cursor height normal in every row of the texts? This is code I'm currently using:

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}];

推荐答案

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

Finally I found a solution that solved my problem.

可以通过将UITextView子类化,然后覆盖caretRectForPosition:position函数来更改光标高度.例如:

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;
}

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

请参见内特的回答.

对于Swift 4.x,请使用caretRect(for position: UITextPosition) -> CGRect.

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

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

这篇关于UITextView lineSpacing使光标高度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:19