xcode+文字支持html元素,iOS使用UITextview实现富文本编辑
代碼使用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!)!]
}
})
myHaq.netDic.removeAll()
varimgIdx =0
forstrinmarkHtmlStr.components(separatedBy:"\n") {
print(str)
//str 注意 iOS12 沒有contains("file:") 存儲圖片標示策略需調整
// iOS12之前:
// iOS12:
if str.contains("file:") {//截取轉化后的htmlStr中的所有img標示
varstr1 = str
print(str1)
ifstr.contains("//Attachment") {
str1 =String(str1[str1.range(of:"")!.upperBound])
}else{//網絡圖片 修改時是后臺傳來的圖片地址
str1 =String(str1[str1.range(of:"")!.upperBound])
}
print(str1)
myHaq.netDic[str1] =UIImageJPEGRepresentation(imgs[imgIdx],1.0)!.base64EncodedString(options:NSData.Base64EncodingOptions.lineLength64Characters)
imgIdx +=1
}
}
myHaq.netDic["markHtmlStr"] = markHtmlStr//數據在myHaq.netDic里 發送網絡請求就ok
以上只是截取代碼部分
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的xcode+文字支持html元素,iOS使用UITextview实现富文本编辑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言编程算法精选,c语言经典程序算法【
- 下一篇: 方法 手写promise_JS探索-手写