2017-10-15 64 views
1

我根據用戶提供的數據動態地在我的UITableView單元格中設置內容。例如,如果用戶不提供圖像,則UIImageView消失以使單元顯示更短。我的問題是,我認爲動態處理我的單元格內容導致重用單元格搞砸了。在UITableView上重新加載數據後,我的UIImageView如何消失?

我確定問題是因爲我從超級視圖中刪除圖像視圖,但是當我重新加載我的表視圖時,它不應該重置嗎?或者我必須以某種方式將它添加回超級視圖?在我走之前,不必要地以編程方式添加一堆約束,處理這個問題的正確方法是什麼?這是我的手機的相關代碼。

func configureItemCell(postTitle: String, postTime: String, postDescription: String, postImageURL: String) { 
     titleLabel.text = postTitle 
     timePostedLabel.text = "\(postTime) by" 

     if postImageURL != "" { 
      postImageView.sd_setImage(with: URL(string: postImageURL), placeholderImage: UIImage(named: "placeholder")) 

     } else { 
      // Remove image view since none was specified 
      postImageView.removeFromSuperview() 

      // Attach constraint for description since image is now gone 
      let descriptionBottomConstraint = NSLayoutConstraint(item: descriptionLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant: -12) 
      NSLayoutConstraint.activate([descriptionBottomConstraint]) 
     } 

     if postDescription == "" { 
      // Shrink distance to 0 since description not showing 
      descriptionTopConstraint.constant = 0 
     } 
    } 

回答

0

簡單的解決方案是使用兩種不同的細胞類型。一個是正​​規的,另一個是特殊的。

override func tableView(_ tableView: UITableView, cellForRowAt 
indexPath: IndexPath) -> UITableViewCell { 
    let item = items[indexPath.section] 
    switch item.type { 
    case .normal: 
     if let cell = tableView.dequeueReusableCell(withIdentifier: "Normal", for: indexPath) as? NormalCell { 
    cell.item = item 
    return cell 
    } 
    case .special: 
     if let cell = tableView.dequeueReusableCell(withIdentifier: "Special", for: indexPath) as? AboutCell { 
    cell.item = item 
    return cell 
    }