UICollectionView CellForItem在滚动时被多次调用,导致单元格文本重叠

时间:2018-06-02 19:57:11

标签: swift uicollectionview

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

最初,所有视图的外观和外观如何: 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
}

1 个答案:

答案 0 :(得分:1)

由于细胞重新出现,请勿在{{1​​}}

中添加子视图
cellForRow

//

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

中的

cellForRowAt

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