600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > xcode+文字支持html元素 iOS使用UITextview实现富文本编辑

xcode+文字支持html元素 iOS使用UITextview实现富文本编辑

时间:2023-03-21 06:29:37

相关推荐

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!)!]

}

})

Dic.removeAll()

varimgIdx =0

ponents(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)

Dic[str1] =UIImageJPEGRepresentation(imgs[imgIdx],1.0)!.base64EncodedString(options:NSData.Base64EncodingOptions.lineLength64Characters)

imgIdx +=1

}

}

Dic["markHtmlStr"] = markHtmlStr//数据在Dic里 发送网络请求就ok

以上只是截取代码部分

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。