如何将结构值加载到collectionView单元格

时间:2019-07-14 19:40:52

标签: ios swift struct collectionview

如何将结构值加载到集合视图单元格中。

struct Person: Codable {
    let id,name,age,gender: String
}

为人员列表增加价值

func addValues () -> [Person]{
  person =[(Person(id:"0",name:"abcd",age:"27":gender:"male"))]

}

InSide CollectionView控制器

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell
    cell.personImg!.image = UIImage.init(named:personList.imageImage[indexPath.row])

    switch indexPath.row {
    case 0:
        cell.lbl_CompletionName!.text = person[0].id
        break
    case 1:
        cell.lbl_CompletionName!.text = person[0].name
        break
    case 2:
        cell.lbl_CompletionName!.text = person[0].age
        break
    case 3:
        cell.lbl_CompletionName!.text = person[0].gender
        break
    default: break

    }

    return cell

    }

仅获得 id 值,一旦indexpath.row增加,如何需要分配下一个值,例如姓名,年龄,性别。

上面的代码用于提取存储在arraylist中的Struct值。

我不喜欢编写代码的方式。 有没有其他方法可以提取添加到数组列表属性中的结构值并将其加载到collectionview中?

1 个答案:

答案 0 :(得分:0)

您可以在Person中创建一个CustomCollectionViewCell变量,并在cell.person中设置func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell变量。您还需要有一个数组(在下面的例子中,我将其称为people),该数组存储所有Person对象,无论您在哪里显示集合视图(很可能是视图控制器)。

示例:

人员

struct Person: Codable {
    let id,name,age,gender: String
}

馆藏视图单元格

class CustomCollectionViewCell: UICollectionViewCell {

     // Create a Person variable
     var person: Person? {
          didSet {
               guard let person = person else { return }
               // Do something (e.x. set imageView.image = person.image)
          }
     }

}

收藏夹视图

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

   let person = people[indexPath.item]  // This is the array of Persons you need in your view controller
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell
   cell.person = person
   return cell

}
相关问题