2015-10-06 49 views
1

我改變了tableview單元格的選擇顏色,它只適用於第1行及其後的行,但第0行「first」並不表示默認的淺灰色。表格單元格選擇顏色工作在0單元格之後但不是第一行?

我做錯了嗎?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 



    // Configure the cell... 

    let colorView = UIView() 
    let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0) 
    colorView.backgroundColor = green 
    UITableViewCell.appearance().selectedBackgroundView = colorView 


     cell.textLabel?.text = "#" + books[indexPath.row] 

     return cell 
    } 

回答

1

你有沒有意識到,你換所有細胞外觀上與此調用UITableViewCell.appearance().selectedBackgroundView = colorView?因此,每次您的表格視圖請求一個單元格時,您都會創建新視圖,將其稱爲colorView並替換以前創建的所有單元格的selectedBackgroundView?你在做這件事。

移動這個

let colorView = UIView() 
let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0) 
colorView.backgroundColor = green 
UITableViewCell.appearance().selectedBackgroundView = colorView 

viewDidLoad方法。

但是,只有當您需要的不僅僅是選定的單元格的綠色,而是更復雜的東西時也可以。

更好地做到這一點在你的cellForRowAtIndexPath

cell.selectedColor = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0) 
1

如果你只是想改變背景顏色,你並不需要創建一個UIView,並設置背景顏色給它。改爲改變contentView背景,它應該在didSelectRow ...方法中。不cellForRow ..因爲這是爲表視圖加載每一個細胞

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0) 
    tableView.cellForRowAtIndexPath(indexPath)?.contentView.backgroundColor = green 
} 
+1

據,因爲我能理解,@marrioa需要改變選擇顏色 –

+1

好,我想在這種情況下,他使用了錯誤的委託方法。它應該在didSelectRowAt ...委託方法 – Lukas

+1

我會編輯我的答案,這種情況下 – Lukas