自己笔记 感觉直接上代码比较直观,文笔不好也写不好文章
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 显示复杂的页面布局,可用于常见的发帖,发表文章等需求。