我有一个展示日期数组的集合视图。当视图首次加载时,单元格看起来很好,但是在我水平滚动一下后,看起来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
}
答案 0 :(得分:1)
由于细胞重新出现,请勿在{{1}}
中添加子视图cellForRow
//
dateCell.addSubview(dayLabel)
dateCell.addSubview(weekdayLabel)
中的
cellForRowAt
设计将在xib中,或者在init方法中的单元的自定义类