Swift 3、显示HTML文本的部分行

Swift 3, Display some lines of the HTML text

我尝试在 webView 中添加 html 代码:

webView.loadHTMLString(myHTML, baseURL: nil)

但最后一行显示被裁剪:

在我的 webView 中隐藏裁剪后的底线的最佳方法是什么?

我推荐你也使用 UILabel

完整示例

ViewController.swift

import UIKit

class ViewController: UIViewController {

    var label: UILabel?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.lightGray

        var bounds = view.bounds
        bounds.origin.y = 44
        bounds.size.height = 100
        label = UILabel(frame: bounds)
        label?.backgroundColor = UIColor.white
        view.addSubview(label!)

        let filename = "HTMLPage.html"
        if let path = Bundle.main.path(forResource: filename, ofType: nil) {
            do {
                let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
                label?.attributedText = text.htmlToAttributedString
                label?.numberOfLines = 5
                label?.lineBreakMode = .byTruncatingTail
            } catch {
                print("Failed to read text from \(filename)")
            }
        } else {
            print("Failed to load file from app bundle \(filename)")
        }
    }

}

extension String {

    var htmlToAttributedString: NSAttributedString? {
        do {
            let data = self.data(using: String.Encoding.utf8, allowLossyConversion: true)
            if let d = data {
                let str = try NSAttributedString(data: d,
                                                 options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                                 documentAttributes: nil)
                return str
            }
        } catch {
        }
        return nil
    }
}

HTMLPage.html

<div style="font-family:'Helvetica'; font-size: 11pt;"><div class="feed-description"><p>The apple tree (Malus pumila, commonly and erroneously called Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple.  <a href="..." target="_blank">link</a> It is cultivated worldwide as a fruit tree, and is the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe, and were brought to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek and European Christian traditions. <a href="..." target="_blank">link</a> text text text</p></div></div>

结果