我有一个UICollectionViewCell。在这个单元格中,我有一个名为cellTitle的标签,我在类的顶层声明了这个标签:

var cellTitle = UILabel()

我在cellForItemAtIndexPath方法中更改每个单元格中此标签的文本:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
cellTitle = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 160))
cellTitle.numberOfLines = 3
cell.contentView.addSubview(cellTitle)
switch indexPath.item {
    case 0:
        cellTitle.text = definitions[0]
    case 1:
        cellTitle.text = definitions[1]
    case 2:
        cellTitle.text = definitions[2]
    case 3:
        cellTitle.text = definitions[3]
    case 4:
        cellTitle.text = definitions[4]
    case 5:
        cellTitle.text = definitions[5]
    case 6:
        cellTitle.text = definitions[6]
    case 7:
        cellTitle.text = boatTypes[0]
    case 8:
        cellTitle.text = boatTypes[1]
    case 9:
        cellTitle.text = boatTypes[2]
    case 10:
        cellTitle.text = boatTypes[3]
    case 11:
        cellTitle.text = boatTypes[4]
    case 12:
        cellTitle.text = boatTypes[5]
    case 13:
        cellTitle.text = boatTypes[6]
    case 14:
        cellTitle.text = "Press to quit game. Time left: \(timerText) seconds"
    default:
        break
    }
    return cell
}

如您所见,在cell14上,我没有将文本设置为数组中的元素。我使用的是我创建的计时器中的timerText,它以1秒的间隔倒数。问题是cell14中timerText的文本没有更新,它只是停留在我第一次设置的位置,即45。如何仅为cell14创建不会导致错误的刷新方法?谢谢你的支持!

最佳答案

让您的计时器为该单元格调用reloadItemsAtIndexPaths

myCollectionView.reloadItemsAtIndexPaths([NSIndexPath(forItem: 14, inSection: 0)])

我已经更新了您的collectionView:cellForItemAtIndexPath:以将tag添加到UILabel以便可以重用它。我还把你常见的病例都放在了switch里。我还没整理好,但应该很接近。
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let specialTag = 123
    var cellTitle: UILabel

    if let oldCell = cell.contentView.viewWithTag(specialTag) as? UILabel {
        // Just reuse the label if it is already there
        cellTitle = oldCell
    } else {
        // Don't have one?  Add a new label and give it a tag so we can find it
        // the next time.
        cellTitle = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 160))
        cellTitle.numberOfLines = 3
        cellTitle.tag = specialTag
        cell.contentView.addSubview(cellTitle)
    }
    switch indexPath.item {
    case 0...6:
        cellTitle.text = definitions[indexPath.item]
    case 7...13:
        cellTitle.text = boatTypes[indexPath.item - 7]
    case 14:
        cellTitle.text = "Press to quit game. Time left: \(timerText) seconds"
    default:
        break
    }
    return cell
}

08-04 15:57