无法更新 UICollectionView 单元格中的标签 (Swift)

Unable to update label in UICollectionView cell (Swift)

我的应用程序在 ContainerView 中有一个 UICollectionViewController,我无法在任何自定义单元格中 change/update 标签。我的 viewDidLoad 函数加载只是加载一个数组,其中包含 5 个包含图像和标签的自定义对象实例。这个以后会作为我的数据源。

override func viewDidLoad()
{
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    //self.clearsSelectionOnViewWillAppear = false

    // Register cell classes
    //self.collectionView!.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    // Do any additional setup after loading the view.
    self.collectionView!.allowsMultipleSelection = true;

    //UICollectionView setup
    let singleImage = UIImage(named: "IMG_0800.jpg")
    let imageName = "Original"

    for var i=0; i<5; i++
    {
        let vehicleObject = VehicleObject(image: singleImage!, label: imageName)
        arrayOfVehicles.append(vehicleObject)
    }
}

此方法似乎有效,但部分有效。当应用 运行s 确实显示了五张图片,但标签仍然显示 "Label" 这是故事板原型的默认值,但故事板中的默认照片被替换为我加载的照片在 viewDidLoad 函数中。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    //Configure the cell
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

    cell.backgroundColor = UIColor .blackColor()
    cell.selectedBackgroundView = UIView(frame: CGRectMake(0, 0, 300, 300))
    cell.selectedBackgroundView?.backgroundColor = UIColor .redColor()

    cell.imageView.image = arrayOfVehicles[indexPath.row].vehicleImage
    cell.imageLabel = arrayOfVehicles[indexPath.row].vehicleLabel

    return cell
}

最后,此方法对单元格中的 UILabel 完全没有影响。当它 运行s 时,println 调用显示的正是我所期望的(更新后的值),但集合视图单元格中的标签根本没有更新。它始终与情节提要中初始化的内容相同。图像更新,标签没有。我 运行 无法在互联网上搜索此内容!

func renameAllCellLabels()
{   
    var selectedItemsIndexPaths = collectionView?.indexPathsForVisibleItems()
    for var i=0; i < selectedItemsIndexPaths?.count; i++
    {
        let selectedItemIndexPath = selectedItemsIndexPaths?[i] as! NSIndexPath
        let cell = collectionView?.cellForItemAtIndexPath(selectedItemIndexPath) as! MyCollectionViewCell

        let singleImage = UIImage(named: "Shelby.jpg")

        let i = selectedItemIndexPath.row
        println(i)
        println(arrayOfVehicles[i].vehicleLabel.text)
        println(cell.imageLabel.text)

        arrayOfVehicles[i].vehicleLabel.text = "Updated"
        cell.imageLabel.text = "Updated"

        arrayOfVehicles[i].vehicleImage = singleImage
        cell.imageView.image = singleImage

        println(arrayOfVehicles[i].vehicleLabel.text)
        println(cell.imageLabel.text)
        println()
    }
    collectionView?.reloadItemsAtIndexPaths(selectedItemsIndexPaths!)
}

您应该使用数据模型中的信息更新现有标签,而不是每次都创建一个新标签:

cell.imageLabel.text = // The text…