滚动时UITableView与自动布局不平滑

问题描述:

我使用XIB文件来设计我的UITableView中的单元格。我也使用dequeue mecanism,例如:let cell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleTableViewCell。我预先计算了我的ViewController的viewDidLoad中的所有行高,因此方法func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat立即返回正确的值。所有这些工作。滚动时UITableView与自动布局不平滑

在我的UITableViewCell中,我使用了许多动态高度标签(lines = 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) 
      } 
     } 
    } 
} 

我所有的图片在后台线程下载,所以滚动时没有图像加载。

的布局是在我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模拟器上,绝对没有滞后,非常平滑。

任何idead?也许是因为我使用UIStackView来嵌入我的标签?我这样做是因为在空标签时隐藏标签更容易,所以其他元素向上移动,以避免在空标签处留有间距。

我尝试了很多事情,但不能得到tableview滚动顺利,任何帮助将不胜感激。

+0

谢谢你的提示。我问,因为可能有人有同样的问题,这会对我有很大的帮助。无论如何,我会试着找出仪器。 – Tiois

+0

顺便说一句,滞后不是在几秒钟内......但是当滚动缓慢时,您可以看到滚动在下一个表格出现之前不是流体。希望仪器公司会帮我弄清楚,我还没有使用的工具。我应该使用什么工具工具? – Tiois

+0

我做了一些优化。我调整了我的图像大小,使UIImage具有与UIImageView相同的大小。我在prepareForReuse方法中在我的UIImageView中加载了一个临时占位符UIImage,因此如果一个单元没有要显示的图像,它将显示此占位符。这张图片是从“磁盘”加载的,造成了一些延迟。我现在使用相同的UIImage实例来避免这种情况。现在,唯一的问题是,当从NIB创建一个新的单元(没有要出队的单元)时,会有一个小滞后,当有足够的单元出队时这个滞后不存在。有任何解决这个问题的方法吗? – Tiois

我所有的优化都使它在6s设备上几乎100%流畅,但在5s上,它确实不平滑。我甚至不想测试4s设备!使用多个多行标签时,达到了自动布局性能限制。

对Time Profiler进行深入分析后,结果是动态标签高度(在我的情况下为3)与它们之间的约束,并且这些标签具有归属文本(用于设置行高度,但这不是瓶颈),看起来延迟是由UIView :: layoutSubviews引起的,它会呈现标签,更新约束等等。这就是为什么当我不改变标签文本时,一切都很流畅。这里唯一的解决方案就是不要在自定义UITableViewCell子类的layoutSubviews方法中以编程方式使用autolayout和layout de子视图。

对于那些想知道如何做到这一点,我实现了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() 
    } 

} 

在我的视图控制器的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() 

    } 
} 
+0

嗨,我有一个类似的问题,即使自动布局,图像背景加载和压缩,滚动并不平滑。但是,如果预先计算所有细胞,并且如果有很多细胞(如数千个细胞),那么表的初始负荷是不是会很慢? – dickyj

+0

在这种情况下,我会预先计算当前显示的单元格的10个下一个单元格。 – Tiois

+0

但是,一旦您计算了接下来的10个单元,会不会影响垂直滚动条的位置?我的意思是这可能会导致再次跳动? – dickyj