问题描述
我在 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 导致段落行之间的光标高度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!