UITextView 加载富文本(带图文)

1、前言

iOS 10.0
Xcode 13.3.1
SwiftRichString  4.0.0

本来我们UI制定的图上面只是文字,但是由于后台输入框能添加图片,我们原定只加载文本,变成了富文本,样式如下

请添加图片描述

1.2、情景2 一个AI互动页面,简单的虚拟聊天,聊天内容可能会出现多个图片 请添加图片描述

2 解决方法

2.1 计算富文本宽高

因为富文本中带有网络图片,所以要计算出图片宽度的富文本宽高
1、网上很多方法我看都计算不出来,我再 img 标签后面给网络图片添加个宽度,就可以了(可能是因为我们的富文本不规范吧,img标签都没有设置width)
2. 计算宽高时候发现,p标签会导致高度偏高,所以我给替换掉了(如有大佬知道原因,或者能给出其他方法,请留言@我)


/// html字符串   文本域宽度  字体大小
public func getAttriSize(text: String, width: CGFloat, font: UIFont) -> CGSize {
    
    
    var html = "<head><style>img{max-width:\(width) !important;height:auto}</style></head>\(text)"
    html = html.replacingOccurrences(of: "<img", with: "<img width=\"\(width)\"")
    html = html.replacingOccurrences(of: "<p>", with: "")
    html = html.replacingOccurrences(of: "</p>", with: "")
    
    var htmlString: NSMutableAttributedString? = nil
    do {
    
    
        if let data = html.data(using: .utf8) {
    
    
            htmlString = try NSMutableAttributedString(data: data, options: [
            NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
            ], documentAttributes: nil)
        }
    } catch {
    
    
    }
    // 设置富文本字的大小
    htmlString?.addAttributes([
    NSAttributedString.Key.font: font
    ], range: NSRange(location: 0, length: htmlString?.length ?? 0))

    // 设置行间距
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 6
    htmlString?.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: htmlString?.length ?? 0))
    
    let attri = htmlString ?? NSMutableAttributedString(string: html)
    let htmlSize = attri.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
                                      options: [.usesLineFragmentOrigin, .usesFontLeading],
                                      context: nil).size 
    return htmlSize
}

2.2 使用UITextView 加载富文本

private lazy var textView: UITextView = {
    
    
    let newTextView = UITextView()  
	textView.textContainer.lineFragmentPadding = 0.0
    newTextView.backgroundColor = .clear
    newTextView.isUserInteractionEnabled = false
    return newTextView
}()

2.3 使用 SwiftRichString 生成 NSMutableAttributedString 进行加载

如果只使用 NSMutableAttributedString,网络图片会导致加载不出来的情况,我看网络上博客都说能加载出来,但是我这边确实加载失败,只是展示一个请添加图片描述
转换代码

  1. 标签中的 src 要替换成 url
  2. br 标签替换成 \n 才能换行
import SwiftRichString 

///SwiftRichString 转换 NSMutableAttributedString 生成器
///html字符串   字体大小
func settingHtmlAttri(text: String, font: UIFont) -> NSMutableAttributedString {
    
    
    let styleGroup = StyleGroup(base: Style {
    
    
        $0.font = font
        $0.color = RGBA(51)
        $0.lineSpacing = 6
    })
    var html = text
    html = html.replacingOccurrences(of: "src", with: "url")
    html = html.replacingOccurrences(of: "<br>", with: "\n")
    html = html.replacingOccurrences(of: "<br/>", with: "\n")
    return html.set(style: styleGroup)
}

3 遇到的问题

3.1 富文本宽度计算

3.1.1 计算耗时,慎用

少量加载可以无视,大量就要慎重了,(如有大佬有解决方法,请留言@我)

3.2.2 计算宽度精度问题

宽度精度会丢失一点点,如要使用,稍微添加0.5的宽度可无视

3.2 UITextView 加载问题

3.2.1 UITextView有内边距,左右间距处理

默认左右间距有5px, 使用下面方法取消左右间距

textView.textContainer.lineFragmentPadding = 0.0

3.2.1 UITextView有内边距,上下间距处理

默认上下间距有8px, 使用下面方法取消上下间距

textView.textContainerInset = .zero

但是,有网络图片的情况下,可能会出现问题(我的部分富文本出现了问题)
UITextView 内部位置上移 请添加图片描述
大致情况如下图所示,设置可编辑状态,输入浮标明显比字体偏下,字体大致向上便宜了1px~2px
在这里插入图片描述
解决方法:建议设置上下边框高度时候注意!设置UITextView frame时候不要忘记添加上下边框距离

3.3 图片问题

图片被限制了宽度来计算高度,所以对图片过小、过长加载非常不友好(如果有更好的加载方法,敬请留言)

猜你喜欢

转载自blog.csdn.net/u014651417/article/details/124745679