如何创建一个每秒刷新一次UICollectionViewCell的方法?

时间:2014-12-23 22:37:05

标签: swift label nstimer uicollectionviewcell reloaddata

我有一个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
}

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

1 个答案:

答案 0 :(得分:0)

让您的计时器例程为该单元格调用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 } 中删除了您的常见案例。我还没有编译过这个,但它应该很接近。

{{1}}