UITextView自定义文字属性后 光标自动跳到末尾的问题

本文介绍如何在iOS应用中使用UITextView控件自定义文字大小、行间距等属性,并解决了编辑过程中光标自动跳转的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用 UITextView 控件中,我们经常需要自定义文字的大小、行间距等属性,让用户输入文字时可以按照设置好的文字属性显示。

- (void)textViewDidChange:(UITextView *)textView {    
    // 设置content格式
    // 字体
    UIFont *font = self.font;
    
    // 设置格式属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; //行间距
    paragraphStyle.firstLineHeadIndent = font.pointSize * indentNumber; //首行缩进宽度
    paragraphStyle.alignment = NSTextAlignmentJustified;
    NSDictionary *attributes = @{
        NSFontAttributeName:font,
        NSParagraphStyleAttributeName:paragraphStyle
    };
    self.attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:attributes];
}

只是实现了上述操作后,我发现了一个奇怪的问题,如果在已经存在的文字中间添加文字,每次输入之后光标都会提动跳到末尾去。最后只能通过代码控制光标的位置,来解决了这个问题。

    // 记录当前光标
    NSUInteger loc = self.selectedRange.location;
    NSUInteger len = self.selectedRange.length;
    
    // 字体
    UIFont *font = self.font;
    
    // 设置格式属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; //行间距
    paragraphStyle.firstLineHeadIndent = font.pointSize * indentNumber; //首行缩进宽度
    paragraphStyle.alignment = NSTextAlignmentJustified;
    NSDictionary *attributes = @{
        NSFontAttributeName:font,
        NSParagraphStyleAttributeName:paragraphStyle
    };
    self.attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:attributes];
    
    // 重设之前光标
    // 解决设置了属性后 光标自动跳转到最后的问题
    self.selectedRange = NSMakeRange(loc, len);
    
    // 并设置textview滚动到光标位置
    // 解决因之前光标跳转到最后 导致的问题
    [self scrollRangeToVisible:self.selectedRange];

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值