我在用着NSMutableParagraphStyle
in my UITextview
用于在每行文本之间添加行间距。
当我在文本视图中输入内容时,光标高度是正常的。但是当我将光标位置移动到第二行(不是最后一行)上的文本时,光标高度变得更大。
我应该怎么做才能使每行文本中的光标高度正常?
这是我当前正在使用的代码:
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}];
最后我找到了解决我的问题的解决方案。
可以通过子类化来更改光标高度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 https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrectforposition
更新:Swift 2.x 或 Swift 3.x
See 内特的回答 https://stackoverflow.com/a/34537839/1467988.
更新: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://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrect
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)