【发布时间】:2020-05-22 11:55:30
【问题描述】:
我想从集合视图中制作一个简单的日历。 [在此处输入图片描述][1][1]:https://i.stack.imgur.com/1yXhL.jpg 但是当我选择一个单元格并开始滚动时,单元格会自动取消选择。这是我的集合视图代码。
`let todayColor = UIColor(red: 242/255, green: 56/255, blue: 15/255, alpha: 1)
let otherDayColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1)
var now = Date()
var day = DateFormatter()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellID", for: indexPath) as! CalenderCell
cell.layer.cornerRadius = 5
cell.backgroundColor = otherDayColor
if indexPath.row == 0{
cell.backgroundColor = todayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: Date()) - 1])
cell.dateLabel.text = now.string(format: "dd")
}
else if indexPath.row == 1{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 1)) - 1])
cell.dateLabel.text = myCalender(numDay: 1).string(format: "dd")
}
else if indexPath.row == 2{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 2)) - 1])
cell.dateLabel.text = myCalender(numDay: 2).string(format: "dd")
}
else if indexPath.row == 3{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 3)) - 1])
cell.dateLabel.text = myCalender(numDay: 3).string(format: "dd")
}
else if indexPath.row == 4{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 4)) - 1])
cell.dateLabel.text = myCalender(numDay: 4).string(format: "dd")
}
else if indexPath.row == 5{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 5)) - 1])
cell.dateLabel.text = myCalender(numDay: 5).string(format: "dd")
}
else if indexPath.row == 6{
cell.backgroundColor = otherDayColor
cell.dayLabel.text = (day.shortWeekdaySymbols[Calendar.current.component(.weekday, from: myCalender(numDay: 6)) - 1])
cell.dateLabel.text = myCalender(numDay: 6).string(format: "dd")
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath){
if indexPath.row == 0{
cell.backgroundColor = todayColor
}
else{
cell.backgroundColor = UIColor.systemGreen
}
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath){
cell.backgroundColor = otherDayColor
}
}`
【问题讨论】:
-
单元格在退出屏幕然后进入时取消选择?
标签: ios swift uicollectionview uicollectionviewcell swift5