2015-12-27 66 views
0

假設我有一個十六進制顏色列表:{#5375ab, #D673DD, #fca565, #4f70a6, #f86cb5, #b9f3cd, #eff8a5, #f4adf9, #fe502e, #5375ab}循環顏色列表並將它們設置爲單元格背景顏色| UITableView | Objective-C

在我的UITableView中,有沒有辦法循環訪問顏色列表並將每個單元格設置爲其中一種顏色?

例如背景顏色將是這樣:

Cell 1 - backgroundColor: #5375ab 
Cell 2 - backgroundColor: #D673DD 
Cell 3 - backgroundColor: #fca565 

...等等

回答

1

是,使用%模運算符的indexPath.row。在你的cellForRowAtIndexPath執行做類似:

NSArray *colors = @[yourColor1, yourColor2, yourColor3]; 
int colorIndex = indexPath.row % colors.count; 

cell.backgroundColor = colors[colorIndex]; 
+0

你知道如何格式化顏色,讓他們被識別爲十六進制顏色?我遇到以下代碼錯誤:'NSArray * colors = @ [@「#5375ab」,@「#D673DD」,@「#fca565」,@「#4f70a6」,@「#f86cb5」,@「 #b9f3cd「,@」#eff8a5「,@」#f4adf9「,@」#fe502e「,@」#5375ab「,@」#ffffff「];' – jape

+0

@jape或者http://stackoverflow.com/questions/ 1560081 /如何創建一個十六進制字符串的uicolor,或者簡單地查看rgb中的實際顏色,如果它們不是動態的,請事先創建它們。 – luk2302

+0

將它們設置爲'[UIColor colorWithRed ...]應該工作,對吧?另外,我是否需要與行一樣多的顏色?它似乎並沒有爲我工作 – jape