我在UITextview
中使用NSMutableParagraphStyle
在每行文本之间添加行空间。
当我在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}];
发布于 2013-12-01 19:30:13
最后,我找到了一个解决问题的方法。
可以通过将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
更新: 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
https://stackoverflow.com/questions/20207961
复制相似问题