iOS利用NSAttributedString实现图文混排效果示例

2020-01-21 02:10:26王冬梅

7-为文本添加图片附件


 // 插入图片附件
 NSTextAttachment *imageAtta = [[NSTextAttachment alloc] init];
 imageAtta.bounds = CGRectMake(0, 0, 375, 180);
 imageAtta.image = [UIImage imageNamed:@"360"];
 NSAttributedString *attach = [NSAttributedString attributedStringWithAttachment:imageAtta];
 [attributedString insertAttributedString:attach atIndex:0];

8-为文本设置段落属性


 // 段落样式
 NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
 // 行间距
 [style setLineSpacing:3];
 // 段落间距
 [style setParagraphSpacing:6];
 // 首行缩进
 [style setFirstLineHeadIndent:25];
 [attributedString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(1, textString.length)];

9-添加网址链接


 // 网址链接
 NSRange urlRange = [textString rangeOfString:@"yunpan.360.cn"];
 [attributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://www.easck.com/pre>

10-通过UITextViewDelegate代理方法,监听URL和附件的点击


 #pragma mark ----------UITextViewDelegate----------
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
 NSLog(@"%@",URL);
 return YES;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
 NSLog(@"%@",textAttachment.image);
 return YES;
}

补充:常用属性字符串属性


 // 字体
 NSFontAttributeName    // UIFont, default Helvetica(Neue) 12
 // 段落
 NSParagraphStyleAttributeName  // NSParagraphStyle, default defaultParagraphStyle
 // 文字颜色
 NSForegroundColorAttributeName // UIColor, default blackColor
 // 背景颜色
 NSBackgroundColorAttributeName // UIColor, default nil: no background
 // 描边颜色
 NSStrokeColorAttributeName  // UIColor, default nil: same as foreground color
 // 描边宽度
 NSStrokeWidthAttributeName  // NSNumber containing floating point value, default 0
 // 阴影
 NSShadowAttributeName    // NSShadow, default nil: no shadow
 // 附件
 NSAttachmentAttributeName   // NSTextAttachment, default nil
 // 链接URL
 NSLinkAttributeName    // NSURL (preferred) or NSString
 // 基线偏移量
 NSBaselineOffsetAttributeName  // NSNumber containing floating point value,default 0
 // 下划线
 NSUnderlineColorAttributeName  // UIColor, default nil: same as foreground color

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。