2017-02-20 45 views
1

我想使用此代碼來突出我的tableview第一單元:麻煩中的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 
    } 
} 

一切似乎確定。但是當我點擊某個單元格時,轉到另一個viewController,然後返回到我的單元格,不知何故第二個單元格已被高亮顯示。所以我多次點擊了我的單元格,發現在我從另一個視圖控制器返回到tableview後,下一個單元格已經高亮顯示(並且在點擊N後,我的所有單元格都變爲帶有邊框的突出顯示)。

我應該如何解決我的代碼突出顯示第一個細胞,即使當我去另一個控制器並返回到我的細胞?

回答

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

此代碼真的不應該在你的視圖控制器。創建的UITableViewCell一個子類...

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 
     } 
    }  
} 

然後在您的cellForRow atIndexPath方法:

cell.hasBorder = indexPath.row == 0 
相關問題