【问题标题】:UICollectionView CellForItemAt being called multiple times on scroll causing cell text to overlapUICollectionView CellForItemAt 在滚动时被多次调用,导致单元格文本重叠
【发布时间】:2018-06-02 19:57:10
【问题描述】:

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

最初,所有视图的外观和外观:

滚动一点后:

滚动很多之后:

这是我的 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
}

【问题讨论】:

  • 细胞被重复使用。不要在cellForItemAt 中使用addSubview()

标签: swift uicollectionview


【解决方案1】:

因为cell resuing,所以不要在cellForRow中添加子视图

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

//

cellForRowAt

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

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

【讨论】:

  • 是的,这有效!谢谢!你知道我怎么能做到,只有一个特定索引处的特定单元格是深灰色,以显示它是一周中的那一天?我遇到了类似的问题,当我滚动时,某些单元格也会变成深灰色。
猜你喜欢
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
相关资源
最近更新 更多