如何 create/call 在 UICollectionView 的 cellForItemAt 中运行

How to create/call functions inside cellForItemAt in a UICollectionView

我是初学者,我觉得这是一个简单的问题。

我的 cellForItemAt 方法非常冗长,我想创建函数来清理它们。

如何创建一个函数来绕过产生错误

cell.nameLabel.text

"Use of unresolved identifier 'cell'"?

例如:

func setAllCellLabels() { 
   cell.nameLabel1.text = "Name1"
   cell.nameLabel2.text = "Name2" 
} 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NameCell", for: indexPath) as! NameCell 
     setAllCellLabels() 
     return cell 
}

需要在子类中创建NameCell(推荐)

class NameCell:UICollectionViewCell {
   func setAllCellLabels() { 
      self.nameLabel1.text = "Name1"
      self.nameLabel2.text = "Name2" 
   }
}

然后在里面调用cellForItemAt

cell.setAllCellLabels()

或者您在 vc 中需要它(不推荐)

func setAllCellLabels(_ cell:NameCell) { 
  self.nameLabel1.text = "Name1"
  self.nameLabel2.text = "Name2" 
}

并称之为

self.setAllCellLabels(cell)

您可以按照 Sh_Khan 所说的方式,将方法添加到您的客户单元 class。或者,您可以实现一个功能,就像您现在在

func setAllLabelsForCell(_ cell: NameCell) {
    cell.nameLabel1.text = "Name1"
    cell.nameLabel2.text = "Name2"
}

请注意,每次都使用完全相同的常量数据配置单元格并不是很有用。您可能想要设置一个数据模型,该模型是要安装到集合视图中每个 indexPath 中的值的数组。然后,您将在 cellForRowAt() 方法中索引到您的数组,提取该单元格的数据,并将其传递给您的单元格配置方法。

假设它是 CellData 类型的结构数组:

struct CellData {
   let label1Text: String
   let label2Text: String
}

那么您的函数可能如下所示:

func setAllLabelsForCell(_ cell: NameCell, withData cellData: CellData) {
    cell.nameLabel1.text = cellData.label1Text
    cell.nameLabel2.text = cellData.label2Text
}

嘿,Xcode很聪明,这种任务Xcode会自动完成。只需按照以下几个步骤:-

1:- Select 代码行(为其创建函数)

2:- 按右键单击,然后转到“Refractor”方法

3:- 点击“提取到方法”。它会自动创建函数,默认情况下,它会从应该提取的地方调用。

请看图中:-

此解决方案在 Xcode 中永久可用。