【发布时间】: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()。