2017-08-28 8 views
0

私は、TableViewでアクティブなオブジェクトに異なるスタイルを設定しようとしています。私は私のオブジェクト(myObject.isActive)のフラグを設定して、このような私のカスタムUITableViewCellでそれを読んでみました。UITableViewCellのスタイルを変更する方法は?

var myArray = [MyObject]() 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as? myCustomCell { 
     if myArray.count > 0 { 
      // Return the cell 
      let myObject = myArray[indexPath.row] 
      cell.updateUI(myObject: myObject) 

      return cell 
     } 
    } 

    return UITableViewCell() 
} 

myCustomCell:のtableViewのデータのロード

func updateUI(myObject: MyObject){ 
    if myObject.isActive { 
     self.selectedCell() 
    } 
} 

func selectedCell() { 
    labelTitle.font = UIFont(name: "Montserrat-Medium", size: 32) 
    labelTitle.textColor = UIColor(hex: 0x64BA00) 
} 

これは素晴らしい作品。しかし、私がtableViewをスクロールすると、他のセルも異なったスタイリングをしています。これをどうすれば解決できますか?

答えて

4

セルが再利用されます。あなたはすべての可能性を扱う必要があります。 がアクティブな場合はupdateUIメソッドでセルが変更されますが、そうでない場合はセルをリセットしないでください。

func updateUI(myObject: MyObject){ 
    if myObject.isActive { 
     selectedCell() 
    } else { 
     resetCell() 
    } 
} 

そして追加:

func resetCell() { 
    // Set the cell's UI as needed 
} 

別のオプションは、表のセルクラスのprepareForReuseメソッドをオーバーライドすることである

はあなたのような何かを必要としています。このメソッドは、セルを初期状態にリセットする必要があります。

関連する問題