nov*_*ung 23 objective-c ios swift
我正在使用NSMutableParagraphStyle我UITextview在每行文本之间添加行间距.
当我在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}];
Run Code Online (Sandbox Code Playgroud)
nov*_*ung 28
最后,我得到了解决我问题的解决方案.
通过继承UITextView,然后覆盖caretRectForPosition:position函数,可以更改光标高度.例如:
- (CGRect)caretRectForPosition:(UITextPosition *)position {
CGRect originalRect = [super caretRectForPosition:position];
originalRect.size.height = 18.0;
return originalRect;
}
Run Code Online (Sandbox Code Playgroud)
文档链接:https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrectforposition
见内特的回答.
对于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
}
}
Run Code Online (Sandbox Code Playgroud)
文档链接:https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrect
Nat*_*olz 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6898 次 |
| 最近记录: |