ios textview间距_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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值