我正在使用表視圖來顯示資料。我只有一個部分,行數是根據JSON回應計數來的
。這里我使用四種顏色(粉色、黃色、綠色、藍色)作為單元格視圖的背景顏色
目前我能夠用一種顏色(黃色)顯示所有單元格。現在我需要用4種(粉色、黃色、綠色、藍色)顏色顯示每個單元格我的意思是,如果有兩個單元格,我需要顯示單元格的背景顏色,一個單元格是粉紅色,另一個是黃色如果有4個單元格,那么4個單元格的背景顏色為粉色、黃色、綠色、藍色如果有8個單元格,那么前4個單元格為粉色、黃色、綠色、藍色,然后后4個單元格為粉色、黃色、綠色、藍色。像這樣。
表視圖單元格的代碼:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.homeData? .result? .recents?.count ? 0 0 ?
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomePostsTableViewCell", for: indexPath) 作為! HomePostsTableViewCell。
cell.selectionStyle = .none
cell.catView.backgroundColor = .yellow
cell.categoryLabel.text = category
return cell.
}
這里所有的單元格都顯示為黃色 cell.catView.backgroundColor = .yellow但是我需要將cell.catView.backgroundColor改為粉紅色、黃色、綠色、藍色。
怎么做?請指導我
。uj5u.com熱心網友回復:
最好的方法是使用%運算子。它將獲得剩余部分并將其與顏色相關聯。
它將看起來像這樣
switch indexPath.row % 4 {
case 0:
cell.catView.backgroundColor = .yellow
case 1:
cell.catView.backgroundColor = .pink
case 2:
cell.catView.backgroundColor = .green
case 3:
cell.catView.backgroundColor = .blue
}
另外,你可以將所有的顏色存盤在一個陣列中,并在其中使用%。
let colors: [UIColor] = [.黃、.粉、.綠、.藍]
cell.catView.backgroundColor = colors[indexPath.row % colors.count] 。
uj5u.com熱心網友回復:
你可以在cellForRowAt方法里面添加這個邏輯。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomePostsTableViewCell", for: indexPath) 作為! HomePostsTableViewCell。
cell.selectionStyle = .none
switch indexPath.row % 4 {
case 0:
cell.catView.backgroundColor = .systemPink
case 1:
cell.catView.backgroundColor = .yellow
case 2:
cell.catView.backgroundColor = .green
case 3:
cell.catView.backgroundColor = .blue
default: break: break.
}
cell.categoryLabel.text = category
return cell.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/311723.html
標籤:
