gpt4 book ai didi

ios - Swift iOS - 选择新单元格时更改旧单元格的背景颜色

转载 作者:行者123 更新时间:2023-11-30 11:09:08 24 4
gpt4 key购买 nike

在开始之前,应该注意的是,如果我在手动选择单元格后没有更改几个月或更长时间,didDeselectItem 确实可以正常工作。

我有一个带有日期表数据(1-31、1-30 或 1-28)的 collectionView。当用户选择一天时,该单元格的背景颜色将变为红色。如果用户转到不同的月份,则 tableData 会重置,并且 cellForItem 会再次触发,因此所有单元格背景颜色都会设置为 UIColor.clear。

为了跟踪最初选择的日期及其月份/年份,我所做的就是创建 3 个变量,这些变量在触发 didSelectItem 时进行初始化。当用户返回到 cellForItem 中的那个月份时,我检查月份和年份是否匹配,如果匹配,则更改当天的背景。效果很好。

问题是,如果我选择不同的日期,其背景颜色确实会更改为红色,但最初选择的日期仍保持红色。因为单元格从未被实际选择过(我只是更改了 cellForItem 中的颜色)didDeselectItem 永远不会触发来更改旧单元格的背景颜色。

当选择新的一天时,如何获得改变其颜色的第一天?

// when a different month is shown some calculations are done to change these but those calculations aren't relevant to the question
var currentMonthIndex = Calendar.current.component(.month, from: Date())
var currentYear = Calendar.current.component(.year, from: Date())

var selectedMonth = 0
var selectedYear = 0
var selectedDay = 0

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dayCell", for: indexPath) as! DayCell

// clears the background color of all the cells when a new month is shown
cell.backgroundColor = UIColor..clear

if selectedMonth == currentMonthIndex && selectedYear == currentYear {

// when coming back to the selected day/month/year this makes sure the selectedDay's background is still red
if indexPath.item == selectedDay {
cell.backgroundColor = .red
}
}

return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

guard let cell = collectionView.cellForItem(at: indexPath) as? DayCell else { return }

cell.backgroundColor = .red

selectedMonth = currentMonthIndex
selectedDay = indexPath.item
selectedYear = currentYear
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

guard let cell = collectionView.cellForItem(at: indexPath) as? DayCell else { return }

cell.backgroundColor = UIColor.clear
}

如果我的问题不清楚,这里有一个例子

用户选择 1/1/2019,当天的背景现在为红色。如果用户转到 2/2019,则表数据将必须更改,因为只有 28 天,因此该月的所有单元格都是清晰的。如果滚动回 1/2019,tableData 会再次更改,因为该月现在有 31 天,因此所有单元格背景颜色都会再次更改为清除。然而,由于 1/2019 的月份和年份与最初选择的年份相匹配,因此在 cellForItem 中,我现在可以自动将 1/1 的背景颜色再次更改为红色。问题是,如果我选择 1/10,它的背景会变为红色,但1/1 仍然保持红色。一旦我选择 1/10,我需要将 1/1 更改为清除。

最佳答案

尝试在 cellForItem 中手动设置单元格的选择状态:

// when coming back to the selected day/month/year this makes sure the selectedDay's background is still red 
if indexPath.item == selectedDay {
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
cell.backgroundColor = .red
}

这样,取消选择方法应该被调用并删除先前选择的单元格的背景颜色。

关于ios - Swift iOS - 选择新单元格时更改旧单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52368615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com