使用UICollectionView时,我遇到更新单个单元格的问题。 当我点击标签时,我希望标签更改为我可以手动分配的不同数字的值。
代码:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//return nameArray.count;
return 81;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell;
switch(flattened[indexPath.item]){
case 1:
cell.labelText.text="1";
case 2:
cell.labelText.text="2";
case 3:
cell.labelText.text="3";
case 4:
cell.labelText.text="4";
case 5:
cell.labelText.text="5";
case 6:
cell.labelText.text="6";
case 7:
cell.labelText.text="7";
case 8:
cell.labelText.text="8";
case 9:
cell.labelText.text="9";
default:
cell.labelText.text="0";
//print(indexPath.item)
}
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
当我运行我的代码时:
答案 0 :(得分:1)
首先在数组中添加这些值
var array:[String] = ["1", "2" ,"3"] //and so on
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}
并在cellforRow
中这样做
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.label.text = self.array[indexpath.row]
}
使用集合视图didSelectItem
获取您要点按的特定单元格
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.array[indexpath.row] = "YOUR VALUE"
//self.collectionView.reloadData()
self.collectionView.reloadItems(at: [indexpath])
}
建议:尝试了解MVC,MVVM和建模 然后尝试这样:https://stackoverflow.com/a/49248513/5589073