我的应用在ContainerView中有一个UICollectionViewController,我无法在任何自定义单元格中更改/更新标签。我的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)
}
}
这种方法似乎有效,但部分有效。当应用程序运行时,确实会显示五个图像,但标签仍然显示“标签”,这是故事板原型的默认值,但故事板中的默认照片将替换为我在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完全没有影响。当它运行时,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!)
}
答案 0 :(得分:2)
您应该使用数据模型中的信息更新现有标签,而不是每次都创建新标签:
cell.imageLabel.text = // The text…