我對 Swift 和一般編程很陌生,所以很抱歉這個簡單的問題:
我想開發一個使用(水平滾動)UICollectionView作為界面的日歷。的每個單元格UICollectionView都應該有一個帶有相應日期和作業日編號的標簽。
為此,我有一個dateArray存盤日期物件的物件。的setupCell-方法是把各個資料到的標簽UICollectionViewCell。
顯示星期日的單元格應該通過與其他單元格不同的背景顏色來突出顯示。
我試圖在cellForItemAt- 方法中實作這個功能,但卡在那里。
我的功能是這樣的:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCollectionViewCell.identifier, for: indexPath) as! MyCollectionViewCell
let dayFormatter = DateFormatter()
let weekdayFormatter = DateFormatter()
dayFormatter.dateFormat = "dd"
weekdayFormatter.dateFormat = "EEE"
cell.setupCell(day: dayFormatter.string(from: dateArray[indexPath.item]), weekday: weekdayFormatter.string(from: dateArray[indexPath.item]))
if Calendar.current.component(.weekday, from: dateArray[indexPath.item]) == 1 {
cell.backgroundColor = UIColor.gray
}
return cell
}
使用此功能,星期日按計劃突出顯示,但前提是我不滾動。最后滾動后,所有單元格都將突出顯示。
我很感謝每一個解決問題的提示。
uj5u.com熱心網友回復:
該UICollectionViewCells的被重用。因此得名dequeueReusableCell。這意味著,例如, index0處的單元格與index處的單元格相同30。當您將 index 處的單元格的顏色設定0為 時UIColor.gray,該單元格30也將為灰色,除非您將其設定為另一種顏色。因為所有單元格都將被重復使用,并且所有單元格最終都會在某個時刻成為“星期日”,它們都會變成彩色。
對此有一個簡單的解決方法,不僅要為您想要的顏色設定顏色,而且還要反其道而行之。
例如:
if Calendar.current.component(.weekday, from: dateArray[indexPath.item]) == 1 {
cell.backgroundColor = UIColor.gray
} else {
cell.backgroundColor = UIColor.white
}
我自己以前沒有嘗試過,但似乎還有另一種方法可以實作這一目標。您還可以在自身中實作prepareForReuse()( docs ) 方法UICollectionViewCell。您可以通過將以下內容添加到單元格來做到這一點:
override func prepareForReuse() {
super.prepareForReuse()
backgroundColor = UIColor.white // Or set to another color you want
}
另一種方法是backgroundColor在setupCell()您為您的單元格創建的中設定。每次重用單元格時都會呼叫它,因此這也可能是執行此操作的好地方。只需應用與上述相同的邏輯(如果周日 -> 灰色,否則 -> 白色)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/390828.html
標籤:迅速 代码 用户界面 uicollectionviewcell
