NSAttributedString: Fit image to container

后端 未结 3 1176
误落风尘
误落风尘 2020-12-31 19:04

I have a NSAttributedString which is made from HTML and it displays some images. The problem is that the images are bigger than the container and I wonder how to fit them in

3条回答
  •  生来不讨喜
    2020-12-31 19:44

    Swift 4.2 : Using the approach of @Nic Hubbard

    let htmlString = "Put Your YourHTML String Here"
    
    let setHeightUsingCSS = "  \(htmlString) "
    
    self.textView.attributedText = setHeightUsingCSS.html2AttributedString
    
    
    extension Data {
        var html2AttributedString: NSAttributedString? {
            do {
                return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
            } catch {
                print("error:", error)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
    }
    
    extension String {
        var html2AttributedString: NSAttributedString? {
            return Data(utf8).html2AttributedString
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
    }
    

    extension reference

提交回复
热议问题