在JSON中我得到了一些html形式的文本。我正在使用NSAtrributed文本在UILable上显示此文本。我已经为UIlable设置了最大行数= 3,Html文本显示正常,但是如果要显示的文本高于3行,我想在第3行的末尾使用省略号(3点......)。省略号没有来,我也试过了paragraphStyle.lineBreakMode = .ByTruncatingTail。
我使用下面提到的函数从html文本创建属性文本。
extension NSMutableAttributedString {
convenience init(html:String , font : UIFont) throws {
guard let data = html.dataUsingEncoding(NSUTF8StringEncoding) else {
throw NSError(domain: "Invalid HTML", code: -500, userInfo: nil)
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Left
paragraphStyle.minimumLineHeight = 19
paragraphStyle.maximumLineHeight = 21
paragraphStyle.lineBreakMode = .ByTruncatingTail
paragraphStyle.paragraphSpacing = 0
paragraphStyle.paragraphSpacingBefore = 0
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedInteger:NSUTF8StringEncoding),NSParagraphStyleAttributeName: paragraphStyle,NSBaselineOffsetAttributeName: NSNumber(float: 0),NSFontAttributeName : font ]
try self.init(data: data, options: options, documentAttributes: nil)
}}
我以下面提到的方式呼叫上面的扩展
var description = "<p>Some Html Text above 3 lines</p>"
self.lblDescription.numberOfLines = 3
self.lblDescription.adjustsFontSizeToFitWidth = false
lblDescription.lineBreakMode = .ByClipping
let trimmed = description.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let htmlText = "<body style='font-family:Gotham-Book ;font-size: 16px';><style>p {margin-bottom: -20px;}</style>\(trimmed)</body>"
let attributedText = try? NSMutableAttributedString(html :htmlText, font: self.lblDescription.font)
self.lblDescription.attributedText = attributedText
我没有得到我错的地方,我尝试过堆栈溢出的解决方案。请有人为我提供解决方案。