我正在使用swift製作時間表應用程序。 我從網站加載我的數據並將其放在collectionView
上。 在第一部分,我把星期幾和第一行,我把類和其他單元格,我把數據從網絡(主題名稱,課堂室...) 如果我輸入時間表視圖,首先一切都很好。 但是,如果向下滾動並向上滾動,則會在不應該顯示的地方打印一些文本。當單元格被重用時,UICollectionViewCell的文本出現在其他地方
這是我collectionView(collectionView: , cellForItemAtIndexPath:)
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
print("\(indexPath.section), \(indexPath.row)")
let dayArray = ["", "월", "화", "수", "목", "금"]
if indexPath.section == 0 {
// Day
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
var titleLabel = UILabel(frame: CGRectMake(0, 0, cell.bounds.width, cell.bounds.height))
cell.contentView.addSubview(titleLabel)
titleLabel.text = dayArray[indexPath.row]
titleLabel.textAlignment = NSTextAlignment.Center
cell.backgroundColor = mainColor
print("day")
return cell
}
if indexPath.row == 0 {
// index
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
var titleLabel = UILabel(frame: CGRectMake(0, 0, cell.bounds.width, cell.bounds.height))
cell.contentView.addSubview(titleLabel)
titleLabel.text = String(indexPath.section)
titleLabel.textAlignment = NSTextAlignment.Center
cell.backgroundColor = mainColor
print("time")
return cell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TimeTableCell
if let timeTableElement = self.timeTable[indexPath.section-1][indexPath.row-1] {
cell.subjectNameLabel.text = timeTableElement.subjectName
cell.subjectNameLabel.adjustsFontSizeToFitWidth = true
cell.classRoomLabel.text = timeTableElement.classRoom
cell.classRoomLabel.adjustsFontSizeToFitWidth = true
} else {
cell.subjectNameLabel.text = ""
cell.classRoomLabel.text = ""
}
cell.backgroundColor = mainColor
print("class")
return cell
}
我使用的是默認UICollectionViewCell
與添加一個標籤子視圖來顯示日期和上課時間和使用自定義TimeTableCell
到顯示班級數據。
我該如何解決這個問題?
我可以在故事板使用不同的resueIdentifier? 另外,如何刪除titleLabel?是否有一個函數在單元被插入時調用? @CoderWang –
我試圖爲TimeTabelCell使用不同的resueIdentifier,但出現錯誤。 libC++ abi.dylib:以NSException類型的未捕獲異常結束 –
是的,當然。在故事板中選擇你的TimeTableCell,並切換到屬性檢查器,檢查第2行,重用標識符應該在那裏。 – CoderWang