gpt4 book ai didi

swift - UICollectionView CellForItemAt 在滚动时被多次调用导致单元格文本重叠

转载 作者:行者123 更新时间:2023-11-28 14:39:14 27 4
gpt4 key购买 nike

我有一个显示日期数组的 Collection View 。当 View 首次加载时,单元格看起来很好,但在我水平滚动一点后,似乎每次都会触发 CellForItemAt 方法,而不是一次,导致单元格的文本与其默认值重叠。我在下面发布了一些屏幕截图:

最初,所有 View 的显示方式和外观: enter image description here

稍微滚动后: enter image description here

多次滚动后: enter image description here

这是我的 CellForItemAt 代码(由于反复试验,它非常困惑):

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let dateCell = calenderView.dequeueReusableCell(withReuseIdentifier: "dateCell", for: indexPath)
dateCell.layer.cornerRadius = 7
let dayLabel = UILabel(frame: CGRect(x: 0, y: 0, width: dateCell.frame.width, height: dateCell.frame.height / 2))
dayLabel.text = "\(Calendar.current.dateComponents([.day], from: dates[indexPath.row]).day!)"
let weekdayLabel = UILabel(frame: CGRect(x: 0, y: dateCell.frame.height / 2, width: dateCell.frame.width, height: dateCell.frame.height / 2))
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EEE", options: 0, locale: NSLocale.current)
weekdayLabel.text = formatter.string(from: dates[indexPath.row])
dayLabel.text = "\(Calendar.current.dateComponents([.day], from: dates[indexPath.row]).day!)"
weekdayLabel.textAlignment = .center
weekdayLabel.font = weekdayLabel.font.withSize(10)
dayLabel.textAlignment = .center
dateCell.addSubview(dayLabel)
dateCell.addSubview(weekdayLabel)
return dateCell
}

最佳答案

因为cell resuing,不要在cellForRow中添加 subview

dateCell.addSubview(dayLabel)
dateCell.addSubview(weekdayLabel)

//

cellForRowAt

if indexPath.row == indexOfGray {
// gray color
}
else {
{
// default color
}

设计将在 xib 中,或者在 init 方法中自定义单元格类

关于swift - UICollectionView CellForItemAt 在滚动时被多次调用导致单元格文本重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660671/

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