【发布时间】:2019-02-10 12:39:57
【问题描述】:
我的单元格是根据 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 个函数中重新加载集合视图数据,calculateOpenTimeSlots()和calculateBookedTimeSlots(),它们的调用方式如下:
第一种情况:在viewDidLoad()我调用这两个函数,
第二种情况:在Firebaseobserver 函数中我只调用calculateBookedTimeSlots(),第三种情况:在从选择表格视图单元格中更改日期我只调用calculateOpenTimeSlots()indidSelectRowAt。
第一种和第三种情况按预期工作,但第二种情况与问题开头所述不同。你们能看出我在哪里撞墙吗?
像往常一样非常感谢。
编辑:
我在单元格的类中添加了一个prepareForReuse,但是当集合视图绘制单元格时,我仍然得到相同的行为。
这是单元格类:
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)
}
}
【问题讨论】:
-
我不明白第一个问题,但对于第二个问题,您需要在 else 块中重置 backgroundColor。您不应该忘记 Cell 正在被重复使用。
-
@RikeshSubedi。感谢您指出。这就是单元格颜色,实际上我已经想到了这个解决方案,但作为一种解决方法,不是正确的做事方式,我仍然需要学习很多东西。至于第一个问题,正如您从打印中看到的那样,我每个循环得到两组打印,您知道为什么吗?
-
非常感谢。我认为通过在属性检查器中设置背景颜色,我不需要在代码中指定它,因为它只会在每次重绘单元格时满足 if 语句时才会更改它。吸取教训。
-
不,仍然无法正常工作。现在我在 2 个不同的日子里有 2 次预订,每次 1 小时,这意味着要比较 4 个时间段并且它运行正确,但是它跳过了第一场比赛..它只得到了第二场比赛..
标签: ios swift uicollectionview