2015-05-28 86 views
2

我試圖使用此link to color cell與此代碼着色在表視圖備用的TableCell:在UITableView中替代UITableViewCell的顏色?

func colorForIndex(index: Int) -> UIColor 
{ 

    let itemCount = stnRepos.count - 1 
    let color = (CGFloat(index)/CGFloat(itemCount)) * 0.6 
    return UIColor(red: 0.80, green: color, blue: 0.0, alpha: 1.0) 
} 

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, 
    forRowAtIndexPath indexPath: NSIndexPath) 
{ 
     var count = stnRepos.count 
     for (var i = 0; i<=count; i++) 
     { 
      if (i % 2 == 0) 
      { 
       cell.backgroundColor = colorForIndex(indexPath.row) 
       println(i) 
      } 
     } 
} 

但最終着色的所有細胞如圖所示的鏈接。

+1

相當明顯。你的計數是什麼? for循環將從0循環到count。即使一旦它進入細胞將被着色。你需要檢查邏輯。 –

+0

stnRepos是我的數組,我將數組的長度賦給count變量。 –

回答

8

我不知道如果我明白你正在嘗試做的,但是,代碼波紋管會只是顏色(使用函數)的白奇者偶數細胞和油漆

func colorForIndex(index: Int) -> UIColor 
{ 
    let itemCount = stnRepos.count - 1 
    let color = (CGFloat(index)/CGFloat(itemCount)) * 0.6 
    return UIColor(red: 0.80, green: color, blue: 0.0, alpha: 1.0) 
} 

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, 
    forRowAtIndexPath indexPath: NSIndexPath) 
{   
    if (indexPath.row % 2 == 0) 
    { 
     cell.backgroundColor = colorForIndex(indexPath.row) 
    } else { 
     cell.backgroundColor = UIColor.whiteColor()() 
    } 
} 

ps,代碼沒有任何出隊和來自單元格的需求和網格,僅舉例說明了在繪製偶數單元的同時對奇數單元進行繪製的邏輯。我希望幫助你

+0

感謝這個作品以及.. ..!我只是把其他顏色放在其他部分現在看起來好多了.. !! –

+0

@IrshadQureshi好消息!與您的應用程序很好運! – Icaro

1

與您的代碼的問題是,您有一個單元格,您着色stnRepos.count次。你應該這樣你的代碼更改爲:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, 
    forRowAtIndexPath indexPath: NSIndexPath) 
{ 
    if (indexPath.row % 2 == 0) 
    { 
     cell.backgroundColor = colorForIndex(indexPath.row) 
    } 
    else 
    { 
     cell.backgroundColor = UIColor.whiteColor() 
    } 
} 

編輯:加入由@IcaroNZ提到的保持,即使細胞離隊

+0

一流.. !!!工作很好...... !!!得到了我需要的...... !!!謝謝...!!!我今天完成了我的所有選票,但明天我肯定會贊成這個答案...! –

+2

@IrshadQureshi不要忘記,如果您將單元出列,那麼當可重用單元格將舊單元緩存在其上時,您將需要重新從單元格中取出單元格。 – Icaro

1

只是可以肯定的預期行爲的else情況..

您是否試圖爲您的tableview設置樣式,以便奇數行具有一種背景顏色,甚至行具有另一種背景顏色?

如果是這樣的話,那麼也許這可以幫助你:

Change color of alternate row in UITableView for iPhone SDK

關於你的代碼,爲什麼它表現爲它...

- tableView:willDisplayCell:forTableColumn:row: 

被調用一次即將顯示之前,您的tableview中的每一行。

在這些調用中,您循環遍歷整個數組,如果當前值爲偶數,則爲表格單元格的背景着色,這意味着當我爲0時,爲背景着色,當我2你也是這樣做的,你對每一行都這樣做......這可能不是你感興趣的東西:-)

正如Peter Tutervai所建議的那樣,你應該檢查tableColumn是奇數還是行爲這

0
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, 
    forRowAtIndexPath indexPath: NSIndexPath) 
    {   
if (indexPath.row % 2 == 0) 
{ 
    cell.backgroundColor = UIColor.gray 
} else { 
    cell.backgroundColor = UIColor.white 
} 

}

0

嘗試改變

cell.backgroundColor = colorForIndex(indexPath.row) 

cell.contentView.backgroundColor = colorForIndex(indexPath.row)