2017-02-20 4 views
1

私はこのコードを使用して、私のテーブルビューの最初のセルを強調しようとしています:のUITableViewで最初のセルを強調表示するとのトラブル、IOS

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
    if indexPath.row == 0 { 
     cell.layer.borderWidth = 0 
     cell.layer.borderColor = nil 

     cell.layer.borderWidth = 2 
     cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor 
    } 
} 

すべてがOKと思われます。しかし、私はいくつかのセルをクリックすると、別のviewControllerに移動し、私のセルに戻って、何とか2番目のセルが既に強調表示されます。だから、私は何度か自分のセルをクリックして、別のView Controllerからtableviewに戻った後、次のセルが既にハイライト表示されていることが分かりました。

他のコントローラに行って自分のセルに戻っても、最初のセルだけをハイライト表示するようにコードを修正する必要がありますか?

答えて

1

細胞が再利用されます。特定の条件に対して任意の属性を設定する場合は、他のすべての条件に対して常にその属性をリセットする必要があります。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
    if indexPath.row == 0 { 
     cell.layer.borderWidth = 2 
     cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor 
    } else { 
     cell.layer.borderWidth = 0 
     cell.layer.borderColor = nil 
    } 
} 
1

elseブランチを実装して、セルのデフォルトレンダリングを追加する必要があります。このような

何か:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
    if indexPath.row == 0 { 
     cell.layer.borderWidth = 2 
     cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor 
    } else { 
     cell.layer.borderWidth = 0 
     cell.layer.borderColor = nil 
    } 
} 
1

このコードは、本当にあなたのビューコントローラであってはなりません。あなたのcellForRow atIndexPath方法に続いて...

class myCell: UITableViewCell { 

    var hasBorder = false { 
     didSet { 
      layer.borderWidth = hasBorder ? 2 : 0 
      layer.borderColor = hasBorder ? UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor : nil 
     } 
    }  
} 

UITableViewCellのサブクラスを作成します。

cell.hasBorder = indexPath.row == 0 
関連する問題