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(attr
}
}
var attrmyString: NSAttributedString {
let attr = NSMutableAttributedString(attr
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(
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.DocumentRe
documentAttributes: nil) else { return nil }
return html
}
}
Comments
Post a Comment