代碼使用swift4 Xcode9及以上
主要思路是
Textview使用NSMutableAttributedString 轉(zhuǎn)化為 html字符 給后臺(tái)
其中圖片另外 截取htmlStr里相應(yīng)的圖片標(biāo)示 組成字典imgs[“標(biāo)示Str”] = “圖片Base64” 給后臺(tái)
再編輯時(shí)拿到后臺(tái)的 帶圖html字符串轉(zhuǎn)為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!)!]
}
})
實(shí)現(xiàn)富文本字體格式
//加黑
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網(wǎng)絡(luò)
let markHtmlStr = myHaq.attStr.toHtmlStr!//轉(zhuǎn)為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:") {//截取轉(zhuǎn)化后的htmlStr中的所有img標(biāo)示
varstr1 = str
print(str1)
ifstr.contains("http://Attachment") {
str1 = String(str1[str1.range(of: "img src")!.lowerBound..<str1.range(of: ".png")!.upperBound])
}else{//網(wǎng)絡(luò)圖片 修改時(shí)是后臺(tái)傳來(lái)的圖片地址
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字符串里圖片標(biāo)識(shí)字符
upCount += 1
if imgs.count == upCount {//上傳圖片完成計(jì)數(shù) 上傳所有后保存html字符串
saveDo()
}
}
imgIdx +=1
}
}