iOS开发-UITextView设置富文本行间距后光标高度问题

属性

iOS中的字体大小,即UIFont的pointSize属性,并不直接对应行高,一般一个字体是10的文本,line height一般为11.89,大约为字体大小的1.2倍,所以按照这个结果来看,iOS字体默认是1.2倍行高。

行间距和行高

  • line space:行间距,直接对应两行文本之间的间距值。
  • line height of font:每一行文字的高度。
  • 行高:每一行的实际高度,= line height of font + line space。
  • 行高倍数:lineHeightMultiple,几倍行高,= 行高 / line height。

UITextView光标问题

设置textView的行间距

        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:textContent];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 6;
        [attr addAttributes:@{NSParagraphStyleAttributeName:style} range:NSMakeRange(0, textContent.length)];
        [attr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:18]
                    range:NSMakeRange(0, textContent.length)];
  • 设置行间距之后,输入时光标高度会变大

如图
截屏 2024-09-09 10.32.53.jpeg
  • UITextView中重写- (CGRect)caretRectForPosition:(UITextPosition *)position 方法
  • //原理 //UITextView遵循了UITextInput协议,其中有返回光标frame的方法
- (CGRect)caretRectForPosition:(UITextPosition *)position {
    CGRect originalRect = [super caretRectForPosition:position];
    originalRect.size.height = self.font.lineHeight + 2.f;
    originalRect.size.width = 2.f;
    return originalRect;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容