UITableView使用自动布局在滚动时不流畅

3
我正在使用XIB文件设计UITableView中的单元格。我还使用dequeue机制,例如:let cell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleTableViewCell。我在我的ViewController的viewDidLoad中预先计算所有行高,所以func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat方法可以立即返回正确的值。这一切都有效。
在我的UITableViewCell中,我使用许多动态高度的标签(行数= 0)。布局如下:

enter image description here

我不使用透明背景,所有的子视图都是不透明的,并且有指定的背景颜色。我使用了 Color Blended Layers(一切都是绿色)和 Color Misaligned Images(没有黄色)。

这是我的cellForRowAtIndexPath方法:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let tableViewSection = tableViewSectionAtIndex(indexPath.section)
    let tableViewRow = tableViewSection.rows.objectAtIndex(indexPath.row) as! TableViewRow

    switch tableViewRow.type! {

    case TableViewRowType.Article :
        let article = tableViewRow.article!

        if article.type == TypeArticle.Article {

            let cell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleTableViewCell
            return cell

        } else {

            let cell = tableView.dequeueReusableCellWithIdentifier("chroniqueCell", forIndexPath: indexPath) as! ChroniqueTableViewCell
            return cell

        }

    default:
        return UITableViewCell()

    }
}

然后,在willDisplayCell方法中:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let tableViewSection = tableViewSectionAtIndex(indexPath.section)
    let tableViewRow = tableViewSection.rows.objectAtIndex(indexPath.row) as! TableViewRow
    let article = tableViewRow.article!

    if cell.isKindOfClass(ArticleTableViewCell) {
        let cell = cell as! ArticleTableViewCell
        cell.delegate = self
        cell.article = article

        if let imageView = articleImageCache[article.id] {
            cell.articleImage.image = imageView
            cell.shareControl.image = imageView
        } else {
            loadArticleImage(article, articleCell: cell)
        }
    } else {
        let cell = cell as! ChroniqueTableViewCell
        cell.delegate = self
        cell.article = article

        if let chroniqueur = article.getChroniqueur() {
            if let imageView = chroniqueurImageCache[chroniqueur.id] {
                cell.chroniqueurImage.image = imageView
            } else {
                loadChroniqueurImage(article, articleCell: cell)
            }
        }
    }
}

所有图片都是在后台线程中下载的,因此滚动时不会有图片加载。

当我设置“article”属性时,我的ArticleTableViewCell中的布局会被修改:cell.article = article

var article: Article? {
    didSet {
        updateUI()
    }
}

我的updateUI函数:

func updateUI() -> Void {

    if let article = article {
        if let surtitre = article.surtitre {
            self.surtitre.text = surtitre.uppercaseString
            self.surtitre.setLineHeight(3)
        } else {
            self.surtitre.hidden = true
        }

        self.titre.text = article.titre
        self.titre.setLineHeight(3)

        if let amorce = article.amorce {
            self.amorce.text = amorce
            self.amorce.setLineHeight(3)
        } else {
            self.amorce.hidden = true
        }

        if let section = article.sectionSource {
            if section.couleurFoncee != "" {
                self.bordureSection.backgroundColor = UIColor(hexString: section.couleurFoncee)
                self.surtitre.textColor = UIColor(hexString: section.couleurFoncee)
            }
        }
    }
}

问题在于设置标签文本时会导致延迟。 setLineHeight 方法将标签文本转换为NSAttributedString以指定行高,但即使删除此代码并仅设置文本标签,显示新单元格时仍会出现轻微的滞后。
如果我删除所有标签设置代码,则单元格将显示默认标签文本,tableview滚动非常平滑,并且高度也正确。每当我设置标签文本时,就会发生延迟。
我正在我的iPhone 6s上运行应用程序。在6s模拟器上,完全没有任何延迟,非常流畅。
有什么想法吗?也许是因为我使用UIStackView嵌入了我的标签?我这样做是因为当标签为空时隐藏标签更容易,因此其他元素向上移动,以避免空标签处的间距。
我尝试了很多事情,但无法使tableview平稳滚动,任何帮助都将不胜感激。

谢谢你的提示。我之所以问是因为可能有人遇到了同样的问题,这会对我非常有帮助。不过我还是会用Instruments来尝试找出问题所在。 - Tiois
顺便说一下,延迟不是以秒为单位的...但是当你慢慢滚动时,你会发现在下一个表格单元格出现之前,滚动并不流畅。希望Instruments能帮助我找出问题,这是我还没有使用过的工具。在Instruments中应该使用哪个工具? - Tiois
我进行了一些优化。我调整了我的图像大小,使UIImage与UIImageView具有相同的大小。在prepareForReuse方法中,我在我的UIImageView中加载了一个临时占位符UIImage,因此如果单元格没有要显示的图像,它将显示此占位符。这个图像是从“磁盘”加载的,导致了一些小延迟。现在,我使用相同的UIImage实例来避免这种情况。现在,唯一的问题是当从NIB创建新单元格时(没有要出列的单元格),会出现一些小的延迟,而当有足够的单元格要出列时,这种情况就不存在了。有什么办法可以解决这个问题吗? - Tiois
当表格显示时,有两个可见单元格。滚动时,第三个单元格出现,而第一和第二个单元格仍然在屏幕上。 - Tiois
不确定是否理解...在heightForRowAtIndexPath中返回了正确的高度,当表格加载时,它会调用3次“section 0,row 0”(cell#1)和4次“section 1,row 0”(cell#2)这个方法,这是在表格显示时可见的两个单元格。有2个nib被实例化(我在我的UITableViewCell的awakeFromNib中打印一个字符串)。我的单元格以正确的高度正确显示。 - Tiois
谢谢你的帮助@matt,我想我必须手动布局子视图。 - Tiois
1个回答

2
我做了一些优化,使得在6s设备上几乎达到了100%的流畅度,但在5s上,效果并不好。我甚至不想在4s设备上测试!当使用多个多行标签时,我已经达到了自动布局性能极限。

通过对时间分析器进行深入分析,结果表明,动态标签高度(在我的情况下为3)与它们之间的约束条件,以及这些标签具有属性文本(用于设置行高,但这不是瓶颈),似乎滞后是由UIView :: layoutSubviews引起的,它渲染标签,更新约束等...这就是为什么当我不改变标签文本时,一切都很流畅。这里唯一的解决方案是不使用自动布局,而是在自定义UITableViewCell子类的layoutSubviews方法中以编程方式布局子视图。

对于那些想知道如何做到这一点的人,我实现了一个没有自动布局和多个具有动态高度(多行)标签的100%平滑滚动。这是我的UITableView子类(我使用基类因为我有2种类似的单元格类型):

//
//  ArticleTableViewCell.swift
//

import UIKit

class ArticleTableViewCell: BaseArticleTableViewCell {

    var articleImage = UIImageView()
    var surtitre = UILabel()
    var titre = UILabel()
    var amorce = UILabel()
    var bordureTop = UIView()
    var bordureLeft = UIView()

    var articleImageWidth = CGFloat(0)
    var articleImageHeight = CGFloat(0)

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.articleImage.clipsToBounds = true
        self.articleImage.contentMode = UIViewContentMode.ScaleAspectFill

        self.bordureTop.backgroundColor = UIColor(colorLiteralRed: 219/255, green: 219/255, blue: 219/255, alpha: 1.0)

        self.bordureLeft.backgroundColor = UIColor.blackColor()

        self.surtitre.numberOfLines = 0
        self.surtitre.font = UIFont(name: "Graphik-Bold", size: 11)
        self.surtitre.textColor = UIColor.blackColor()
        self.surtitre.backgroundColor = self.contentView.backgroundColor

        self.titre.numberOfLines = 0
        self.titre.font = UIFont(name: "PublicoHeadline-Extrabold", size: 22)
        self.titre.textColor = UIColor(colorLiteralRed: 26/255, green: 26/255, blue: 26/255, alpha: 1.0)
        self.titre.backgroundColor = self.contentView.backgroundColor

        self.amorce.numberOfLines = 0
        self.amorce.font = UIFont(name: "Graphik-Regular", size: 12)
        self.amorce.textColor = UIColor.blackColor()
        self.amorce.backgroundColor = self.contentView.backgroundColor

        self.contentView.addSubview(articleImage)
        self.contentView.addSubview(surtitre)
        self.contentView.addSubview(titre)
        self.contentView.addSubview(amorce)
        self.contentView.addSubview(bordureTop)
        self.contentView.addSubview(bordureLeft)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {

        super.layoutSubviews()

        if let article = article {

            var currentY = CGFloat(0)
            let labelX = CGFloat(18)
            let labelWidth = fullWidth - 48

            // Taille de l'image avec un ratio de 372/243
            articleImageWidth = ceil(fullWidth - 3)
            articleImageHeight = ceil((articleImageWidth * 243) / 372)

            self.bordureTop.frame = CGRect(x: 3, y: 0, width: fullWidth - 3, height: 1)

            // Image
            if article.imagePrincipale == nil {
                self.articleImage.frame = CGRect(x: 0, y: 0, width: 0, height: 0)

                self.bordureTop.hidden = false
            } else {
                self.articleImage.frame = CGRect(x: 3, y: 0, width: self.articleImageWidth, height: self.articleImageHeight)
                self.bordureTop.hidden = true
                currentY += self.articleImageHeight
            }

            // Padding top
            currentY += 15

            // Surtitre
            if let surtitre = article.surtitre {
                self.surtitre.frame = CGRect(x: labelX, y: currentY, width: labelWidth, height: 0)
                self.surtitre.preferredMaxLayoutWidth = self.surtitre.frame.width
                self.surtitre.setTextWithLineHeight(surtitre.uppercaseString, lineHeight: 3)
                self.surtitre.sizeToFit()

                currentY += self.surtitre.frame.height
                currentY += 15
            } else {
                self.surtitre.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
            }

            // Titre
            self.titre.frame = CGRect(x: labelX, y: currentY, width: labelWidth, height: 0)
            self.titre.preferredMaxLayoutWidth = self.titre.frame.width
            self.titre.setTextWithLineHeight(article.titre, lineHeight: 3)
            self.titre.sizeToFit()

            currentY += self.titre.frame.height

            // Amorce
            if let amorce = article.amorce {
                currentY += 15

                self.amorce.frame = CGRect(x: labelX, y: currentY, width: labelWidth, height: 0)
                self.amorce.preferredMaxLayoutWidth = self.amorce.frame.width
                self.amorce.setTextWithLineHeight(amorce, lineHeight: 3)
                self.amorce.sizeToFit()

                currentY += self.amorce.frame.height
            } else {
                self.amorce.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
            }

            // Boutons
            currentY += 9

            self.updateButtonsPosition(currentY)
            self.layoutUpdatedAt(currentY)
            currentY += self.favorisButton.frame.height

            // Padding bottom
            currentY += 15

            // Couleurs
            self.bordureLeft.frame = CGRect(x: 0, y: 0, width: 3, height: currentY - 2)
            if let section = article.sectionSource {
                if let couleurFoncee = section.couleurFoncee {
                    self.bordureLeft.backgroundColor = couleurFoncee
                    self.surtitre.textColor = couleurFoncee
                }
            }

            // Mettre à jour le frame du contentView avec la bonne hauteur totale
            var frame = self.contentView.frame
            frame.size.height = currentY
            self.contentView.frame = frame
        }

    }

}

而基类:

//
//  BaseArticleTableViewCell.swift
//

import UIKit

class BaseArticleTableViewCell: UITableViewCell {

    var backgroundThread: NSURLSessionDataTask?
    var delegate: SectionViewController?

    var favorisButton: FavorisButton!
    var shareButton: ShareButton!

    var updatedAt: UILabel!

    var fullWidth = CGFloat(0)

    var article: Article? {
        didSet {
            // Update du UI quand on set l'article
            updateArticle()
        }
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.selectionStyle = UITableViewCellSelectionStyle.None
        self.contentView.backgroundColor = UIColor(colorLiteralRed: 248/255, green: 248/255, blue: 248/255, alpha: 1.0)

        // Largeur de la cellule, qui est toujours plein écran dans notre cas
        // self.contentView.frame.width ne donne pas la bonne valeur tant que le tableView n'a pas été layouté
        fullWidth = UIScreen.mainScreen().bounds.width

        self.favorisButton = FavorisButton(frame: CGRect(x: fullWidth - 40, y: 0, width: 28, height: 30))
        self.shareButton = ShareButton(frame: CGRect(x: fullWidth - 73, y: 0, width: 28, height: 30))

        self.updatedAt = UILabel(frame: CGRect(x: 18, y: 0, width: 0, height: 0))
        self.updatedAt.font = UIFont(name: "Graphik-Regular", size: 10)
        self.updatedAt.textColor = UIColor(colorLiteralRed: 138/255, green: 138/255, blue: 138/255, alpha: 1.0)
        self.updatedAt.backgroundColor = self.contentView.backgroundColor

        self.addSubview(self.favorisButton)
        self.addSubview(self.shareButton)
        self.addSubview(self.updatedAt)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Avant qu'une cell soit réutilisée, faire un cleanup
    override func prepareForReuse() {
        super.prepareForReuse()

        // Canceller un background thread si y'en a un actif
        if let backgroundThread = self.backgroundThread {
            backgroundThread.cancel()
            self.backgroundThread = nil
        }

        resetUI()
    }

    // Updater le UI
    func updateArticle() {
        self.favorisButton.article = article
        self.shareButton.article = article

        if let delegate = self.delegate {
            self.shareButton.delegate = delegate
        }
    }

    // Faire un reset du UI avant de réutiliser une instance de Cell
    func resetUI() {

    }

    // Mettre à jour la position des boutons
    func updateButtonsPosition(currentY: CGFloat) {

        // Déjà positionnés en X, width, height, reste le Y
        var shareFrame = self.shareButton.frame
        shareFrame.origin.y = currentY
        self.shareButton.frame = shareFrame

        var favorisFrame = self.favorisButton.frame
        favorisFrame.origin.y = currentY + 1
        self.favorisButton.frame = favorisFrame
    }

    // Mettre à jour la position du updatedAt et son texte
    func layoutUpdatedAt(currentY: CGFloat) {
        var frame = self.updatedAt.frame
        frame.origin.y = currentY + 15
        self.updatedAt.frame = frame

        if let updatedAt = article?.updatedAtListe {
            self.updatedAt.text = updatedAt
        } else {
            self.updatedAt.text = ""
        }

        self.updatedAt.sizeToFit()
    }

}

在我的ViewController的viewDidLoad方法中,我预先计算了所有行的高度:
// Créer une cache des row height des articles
func calculRowHeight() {
    self.articleRowHeights = [Int: CGFloat]()

    // Utiliser une seule instance de chaque type de cell
    let articleCell = tableView.dequeueReusableCellWithIdentifier("articleCell") as! BaseArticleTableViewCell
    let chroniqueCell = tableView.dequeueReusableCellWithIdentifier("chroniqueCell") as! BaseArticleTableViewCell

    var cell: BaseArticleTableViewCell!

    for articleObj in section.articles {
        let article = articleObj as! Article

        // Utiliser le bon type de cell
        if article.type == TypeArticle.Article {
            cell = articleCell
        } else {
            cell = chroniqueCell
        }

        // Setter l'article et refaire le layout
        cell.article = article
        cell.layoutSubviews()

        // Prendre la hauteur générée
        self.articleRowHeights[article.id] = cell.contentView.frame.height
    }
}

设置请求单元格的行高:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let tableViewSection = tableViewSectionAtIndex(indexPath.section)
    let tableViewRow = tableViewSection.rows.objectAtIndex(indexPath.row) as! TableViewRow

    switch tableViewRow.type! {

    case TableViewRowType.Article :
        let article = tableViewRow.article!
        return self.articleRowHeights[article.id]!

    default:
        return UITableViewAutomaticDimension
    }
}

cellForRowAtIndexPath方法中返回单元格(因为我的tableView中有多种类型的单元格,所以需要进行一些检查):

// Cellule pour un section/row spécifique
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let tableViewSection = tableViewSectionAtIndex(indexPath.section)
    let tableViewRow = tableViewSection.rows.objectAtIndex(indexPath.row) as! TableViewRow

    switch tableViewRow.type! {

    case TableViewRowType.Article :
        let article = tableViewRow.article!

        if article.type == TypeArticle.Article {
            let cell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleTableViewCell
            cell.delegate = self
            cell.article = article

            if let imageView = articleImageCache[article.id] {
                cell.articleImage.image = imageView
                cell.shareButton.image = imageView
            } else {
                cell.articleImage.image = placeholder
                loadArticleImage(article, articleCell: cell)
            }

            return cell

        }

        return UITableViewCell()
    default:
        return UITableViewCell()

    }
}

你好,我和你有类似的问题,即使使用自动布局、图像背景加载和压缩,滚动仍然不流畅。但是如果预先计算所有单元格,并且单元格很多(比如成千上万个),那么表格的初始加载速度不会非常慢吗? - dickyj
在这种情况下,我会预先计算出类似于当前显示的10个单元格中的下一个单元格这样的东西。 - Tiois
但这样做会不会影响垂直滚动条的位置,一旦计算出接下来的10个单元格?我的意思是那可能会再次引起抖动? - dickyj
我觉得它不会抖动。你需要为每个单元格提供预估的行高,可以返回一个平均值。 - Tiois
我尝试预先计算了3000个单元格,到目前为止没有明显的延迟。因此,我将首先尝试这种策略。 - dickyj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接