2017-10-15 7 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

単純な解決策は、2つの異なる細胞タイプを使用することです。 1つは定期的なもので、もう1つは特別なものです。

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 
    } 
関連する問題