我的单元格是根据 timeSlotArray
创建的,以 30 分钟为增量保留所有开放时间段,但根据它的 ID 是否等于任何 bookedTimeSlotsArray< 来获取它的颜色
条目 ID。
如果我选择有预订的日期,它会为单元格设置正确的颜色,但单元格会在重新加载数据时保持该颜色,即使我更改为有其他预订的日期也是如此。
函数是:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeSlotCell", for: indexPath) as! TimeSlotCollectionViewCell
// Configure the cell
cell.timeLabel.text = timeSlotArray[indexPath.row]
cell.cellId = Int("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))
if bookedTimeSlotsArray.count > 0 {
for index in 0...bookedTimeSlotsArray.count - 1 {
let bookingId = bookedTimeSlotsArray[index].bookingId
if cell.cellId == bookingId {
print(" match found")
print("Index is: \(index)")
print("cell time is: \(timeSlotArray[indexPath.row])")
print("time slot cell id is: \(String(describing: cell.cellId))")
print("booking id: \(bookingId)")
cell.backgroundColor = UIColor.red.withAlphaComponent(0.3)
} else {
cell.backgroundColor = UIColor.green.withAlphaComponent(0.8)
}
}
}
return cell
}
我在 2 个函数中重新加载 Collection View 数据,calculateOpenTimeSlots()
和calculateBookedTimeSlots()
,它们的调用方式如下:
第一种情况:在 viewDidLoad()
中我调用了两个函数,
第二种情况:在 Firebase
observer 函数中,我只调用了 calculateBookedTimeSlots()
,第三种情况:在从选择表格 View 单元格更改日期时,我只调用了 calculateOpenTimeSlots()
在 didSelectRowAt
中。
第一种和第三种情况按预期工作,但第二种情况与问题开头所述不同。你们能看出我在哪里撞墙了吗?
像往常一样非常感谢。
编辑:
我在我的单元格类中添加了一个prepareForReuse
,但是当 Collection View 绘制单元格时我仍然得到相同的行为。
这是单元格类:
import UIKit
class TimeSlotCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var timeLabel: UILabel!
var cellId: Int!
override func prepareForReuse() {
super.prepareForReuse()
// Set your default background color, title color etc
backgroundColor = UIColor.green.withAlphaComponent(0.8)
}
}
最佳答案
发现问题。我取消了 cellForItemAt
中 if
语句之后的 else
语句,因为现在 prepareForReuse
正在设置默认单元格。
现在一切都按预期工作。
最终的功能是:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeSlotCell", for: indexPath) as! TimeSlotCollectionViewCell
// Configure the cell
cell.timeLabel.text = timeSlotArray[indexPath.row]
cell.cellId = Int("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))
if bookedTimeSlotsArray.count > 0 {
for index in 0...bookedTimeSlotsArray.count - 1 {
let bookingId = bookedTimeSlotsArray[index].bookingId
if cell.cellId == bookingId {
print(" match found")
print("Index is: \(index)")
print("cell time is: \(timeSlotArray[indexPath.row])")
print("time slot cell id is: \(String(describing: cell.cellId))")
print("booking id: \(bookingId)")
cell.backgroundColor = UIColor.red.withAlphaComponent(0.3)
}
}
}
return cell
}
关于ios - CollectionView 单元格意外行为 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616475/