代码使用swift4 Xcode9及以上
主要思路是
Textview使用NSMutableAttributedString 转化为 html字符 给后台
其中图片另外 截取htmlStr里相应的图片标示 组成字典imgs[“标示Str”] = “图片Base64” 给后台
再编辑时拿到后台的 带图html字符串转为NSMutableAttributedString给Textview 使用enumerateAttribute可以获取图片
之后再保存和新建的保存差不多
主要注意NSAttachment的使用
attStr.enumerateAttribute(NSAttributedStringKey.attachment, in:NSRange.init(location:0, length:myHaq.attStr.length), options:NSAttributedString.EnumerationOptions(rawValue:0), using: { (value, range, stop)in
if let attachImg = (valueas?NSTextAttachment) {
let img = attachImg.image!
print(img)
imgs += [img]//最终处理 获取所有图片
// let attachmentWrapper = attachImg.fileWrapper!
// imgs += [UIImage.init(data: attachmentWrapper.regularFileContents!)!]
}
})
实现富文本字体格式
//加黑
myHaq.texterTypings[NSAttributedStringKey.font.rawValue] = myHaq.isBold ? UIFont.boldSystemFont(ofSize: myHaq.fontSize) : UIFont.systemFont(ofSize: myHaq.fontSize)
//斜体
myHaq.texterTypings[NSAttributedStringKey.obliqueness.rawValue] = sender.tintColor == colorSystem ? 0.25 : 0
//下划线
myHaq.texterTypings[NSAttributedStringKey.underlineStyle.rawValue] = sender.tintColor == colorSystem ? 1 : 0
//颜色
myHaq.texterTypings[NSAttributedStringKey.foregroundColor.rawValue] = colors[tapG.view!.tag]
//大小
myHaq.texterTypings[NSAttributedStringKey.font.rawValue] = myHaq.isBold ? UIFont.boldSystemFont(ofSize: myHaq.fontSize) : UIFont.systemFont(ofSize: myHaq.fontSize)
save网络
let markHtmlStr = myHaq.attStr.toHtmlStr!//转为html字符串
varimgs = [UIImage]()
myHaq.attStr.enumerateAttribute(NSAttributedStringKey.attachment, in:NSRange.init(location:0, length:myHaq.attStr.length), options:NSAttributedString.EnumerationOptions(rawValue:0), using: { (value, range, stop)in
ifletattachImg = (valueas?NSTextAttachment) {
letimg = attachImg.image!
print(img)
imgs += [img]//最终处理 获取所有图片
// let attachmentWrapper = attachImg.fileWrapper!
// imgs += [UIImage.init(data: attachmentWrapper.regularFileContents!)!]
}
})
varimgIdx =0
forstrinmarkHtmlStr.components(separatedBy:"><") {
if str.contains("file:") {//截取转化后的htmlStr中的所有img标示
varstr1 = str
print(str1)
ifstr.contains("//Attachment") {
str1 = String(str1[str1.range(of: "img src")!.lowerBound..<str1.range(of: ".png")!.upperBound])
}else{//网络图片 修改时是后台传来的图片地址
str1 = String(str1[str1.range(of: "img src")!.lowerBound..<str1.range(of: ".jpg")!.upperBound])
}
print(str1)
DCNetSir.upIconImg(imgs[imgIdx]) { [self] fileUrl in
markHtmlStr = markHtmlStr.replacingOccurrences(of: str1, with: "img src=\"\(fileUrl)")//用上传后的图片url替换html字符串里图片标识字符
upCount += 1
if imgs.count == upCount {//上传图片完成计数 上传所有后保存html字符串
saveDo()
}
}
imgIdx +=1
}
}