iOS之UITextView设置行间距

设置UITextView的行间距有多种方法

一、设置静态textview行间距

UITextView不需要输入直接显示非常简单

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, 100, 200)];

    textView.delegate = self;

    textView.text = @"大家好大家好大家好大家好这是一个测试text";

    [self.view addSubview:textView];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 5;// 字体的行间距

    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

NSMutableParagraphStyle这个类,这是设置段落风格的类,有很多属性,请自行查看API

二、动态设置textview行间距

在textview的代理方法中实现动态改变行间距

- (void)textViewDidChange:(UITextView *)textView{
    
    UITextRange *selectedRange = [textView markedTextRange];
    NSString * newText = [textView textInRange:selectedRange]; //获取高亮部分
    if(newText.length>0)
        return;
   
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 4;// 字体的行间距
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:paragraphStyle};
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

这个方法获取高亮部分可以避免输入内容不准确。但是,当删除内容时光标会一直处于最末位。

三、通过属性设置

textView.typingAttributes属性官方文档描述是

应用于用户输入的新文本的属性。
该字典包含用于新输入的文本的属性键(以及相应的值)。当文本视图的选择发生变化时,字典的内容自动被清除。

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, 100, 200)];

    textView.delegate = self;

    [self.view addSubview:textView];

    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];

    paragraphStyle.lineSpacing = 20;// 字体的行间距

    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    textView.typingAttributes = attributes;

但会有光标扩大问题


没有发现相关的属性来设置光标的显示, 使用系统的UITextView暂时解决不了上述问题

四、自定义textview

UITextView遵循了UITextInput协议,其中有返回光标frame的方法
- (CGRect)caretRectForPosition:(UITextPosition *)position,所以我们可以使用自定义的TextView,重写返回光标frame的方法避免光标扩大问题。

- (CGRect)caretRectForPosition:(UITextPosition *)position {
    CGRect originalRect = [super caretRectForPosition:position];

    originalRect.size.height = self.font.lineHeight + 2;
    originalRect.size.width = 3;

    return originalRect;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容