iOS UITextView---NSAttributedString/NSMutableAttributedStrings使用

自己笔记 感觉直接上代码比较直观,文笔不好也写不好文章

static   UITextView * textView = [UITextView new ];

1:NSString  转 NSAttributedString  同时设置富文本行间距

NSString *text =@"string";

NSAttributedString  * textStr =[[NSAttributedString alloc] initWithString:text];

NSMutableAttributedString *textstring = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];

NSRange range1 = [textView selectedRange];

[textstring insertAttributedString:textStr atIndex:range1.location];

//设置行间距

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

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

NSDictionary *attributes = @{

NSFontAttributeName:[UIFont systemFontOfSize:16],

NSParagraphStyleAttributeName:paragraphStyle

};

//光标位置

NSRange range11 = [textView selectedRange];

[textViewstring addAttributes:attributes range:NSMakeRange(0, range11.location)];

textView.attributedText = text string;


2:UITextView 中加入图片

//添加图片

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;

textAttachment.image =ID;

//图片宽度

CGFloat imageWidth = kScreenWidth -KLeft*3;

textAttachment.bounds = CGRectMake(0, 0, imageWidth, textAttachment.image.size.height*imageWidth/textAttachment.image.size.width);

NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;

NSRange range1 = [textView selectedRange];

[string insertAttributedString:textAttachmentString atIndex:range1.location];//为用户指定要插入图片的位置

textView.attributedText = string;

以此类同  同样的方式可以设置换行处理等 操作,用UITextView 显示复杂的页面布局,可用于常见的发帖,发表文章等需求。

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

相关阅读更多精彩内容

友情链接更多精彩内容