html字符串转富文本字符串(Swift 4)

本文介绍了三种使用Swift将HTML字符串转换为NSMutableAttributedString的方法。这些方法包括利用不同的HTML结构(如<head>和<html>标签)来确保正确的样式应用及图片显示。这些技巧对于iOS开发中处理富文本内容特别有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///方法1-->通过'<head>'将html字符串转化为 NSMutableAttributedString
    class func getAttriFrom(str: String) -> NSMutableAttributedString {
        let htmlStr = "<head><style>img{max-width:\(screenWidth-30)px !important; height:auto}</style></head>" + "<div style='font-size:13.7px'>" + str + "</div>"
        print("方法1-->\(htmlStr)")
        let attStr = try? NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf16)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        return attStr ?? NSMutableAttributedString()
    }

    ///方法2<此方法某些图片不会正常显示>-->通过'<html>'htmlStr 转化为 NSMutableAttributedString
    class func getAttriFrom2(str: String) -> NSMutableAttributedString {
        let headerS = "<html lang=\"zh-cn\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, nickName-scalable=no\"></meta><style>img{max-width: 100%; width:auto; height:auto;}body{text-align:justify;font-size:14px !important;}</style></head><body>"
        let endS = "</body></html>"
        let htmlStr = headerS + str + endS
        print("方法2--->\(htmlStr)")
        let attStr = try? NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        return attStr ?? NSMutableAttributedString()
    }
   

    
  ///方法3-->通过'<html>'htmlStr 转化为 NSMutableAttributedString

    class func getAttriFrom3(str: String) -> NSMutableAttributedString {

        let headerS = "<html lang=\"zh-cn\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, nickName-scalable=no\"></meta><style>img{max-width: \(screenWidth-20); !important; height:auto; margin: 0 auto; padding: 10px 10px 10px 0px; width: 100% !important;} body{text-align:justify;font-size:14px !important;}</style></head><body>"
        let endS = "</body></html>"
        let htmlStr = headerS + str + endS
        //print("方法3--->\(htmlStr)")
        var attStr = NSMutableAttributedString()
        do {
            attStr = try NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        } catch {
            print(error)
        }
        return attStr

    }


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值