IOS 实现图文混排
2017-06-11 本文已影响0人
iOS_开发
一、从本地获取txt文档
//从本地取出txt资源文件
do {
text = try NSString(contentsOfFile: NSBundle.mainBundle().URLForResource("haoshengyin", withExtension: "txt")!.path!, encoding: NSUTF8StringEncoding)
text = (text as String).stringByAppendingString("\n")
}catch {}
//设置scrollView自动适应屏幕,不会有scrollView上方白一片的情况
self.automaticallyAdjustsScrollViewInsets = false
二、对textView文档进行操作
// MARK --改变文字大小,颜色,行间距以及段落间距
//创建可变属性字符串
let attributedTextString = NSMutableAttributedString(string: text as String)
//设置段落间距为可变型,设置为1.35倍间距
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.35*y1
//设置可变字符串的属性,1.段落间距,2.范围是整个文本,3设置字体,4.设置颜色
attributedTextString.setAttributes([NSKernAttributeName:1.8*y1,NSParagraphStyleAttributeName:paragraphStyle], range: NSMakeRange(0, text.length))
attributedTextString.setAttributes([NSFontAttributeName:UIFont.boldSystemFontOfSize(18.0*y1),NSForegroundColorAttributeName:UIColor.blackColor()], range: NSMakeRange(0, 18))
//设置textView的基本属性
let textView1 = UITextView(frame:CGRectMake(15*x, 44+20*y1 , self.view.frame.size.width - 30*x, self.view.frame.size.height-44-20*y1))
textView1.font = UIFont(name: "FZZhunYuan-M02S", size: 17.0*y1)
textView1.attributedText = attributedTextString
textView1.showsVerticalScrollIndicator = false
textView1.editable = false
textView1.scrollEnabled = true
self.scrollView.addSubview(textView1)
三、设置图片为附件加入可变文本当中去
// MARK --设置图片为附件
let string = NSMutableAttributedString(attributedString: textView1.attributedText)
//创建属性字符
let textAttachment = NSTextAttachment(data: nil, ofType: nil)
//设置属性图片
textAttachment.image = UIImage(named: "hsy.png")
//设置属性布局位置
textAttachment.bounds = CGRectMake(0, 0 , self.view.frame.size.width-30*x, 300*y1)
//将属性字符设置为附件
string.insertAttributedString(NSAttributedString(attachment: textAttachment), atIndex: self.text.length)
//将属性文字加入到textView当中
textView1.attributedText = string