String had html elements want to display with trim some substring in iOS swift

 Problem:

I'm having my webview with some html content and i had the html string.I want to trim the string with my limit and also change the attributes of the string to some new attributes.How can i achieve that?


Solution:

extension NSMutableAttributedString {

    func prefix(_ maxLength: Int) -> NSMutableAttributedString {

        guard maxLength > 0 else { return NSMutableAttributedString() }

        guard maxLength < self.length else { return self }


        let prefixRange = NSRange(location: 0, length: min(maxLength, self.length))

        let prefixAttributedString = self.attributedSubstring(from: prefixRange)

        return NSMutableAttributedString(attributedString: prefixAttributedString)

    }


}



    var attrmyString: NSAttributedString {

        

        let attr =  NSMutableAttributedString(attributedString: self.htmlAttributedString() ?? NSAttributedString(string: ""))

        let trimmed = attr.prefix(histNoteMaxLength)

        let attributes: [NSAttributedString.Key: Any] = [

            .foregroundColor: UIColor().mycolor(), // Text color

            .font: UIFont().medium() // Font style

        ]

        let range = NSRange(location: 0, length: trimmed.length)

         trimmed.addAttributes(attributes, range: range)

        return trimmed

    }



extension String {

    func htmlAttributedString() -> NSAttributedString? {

        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

        guard let html = try? NSMutableAttributedString(

            data: data,

            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],

            documentAttributes: nil) else { return nil }

        return html

    }

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

store cgpoint in userdefaults iOS swift