iOS集合视图

  1. 转到Main.storyboard,添加“收藏夹视图”和“收藏夹视图单元格”。
  2. 将图像添加到“ Assets.xcassets”文件夹中。
  3. 将“ ImageView”和“ Label”添加到集合视图单元格。 根据需要调整大小。
  1. 设置“集合视图单元格”的标识符。
  2. 创建一个新文件,类型为“ UICollectionViewCell”。 控件将图像视图和标签从集合视图单元格拖动到此新文件。
  3. 转到视图控制器swift文件。 控件拖动“集合视图”到视图控制器。 扩展文件以包括“ UICollectionViewDelegate”和“ UICollectionDataSource”。
  4. 在“ viewDidLoad”函数中,添加以下行
    FeaturedCollectionView.delegate =自我
    FeaturedCollectionView.dataSource =自我
  5. 您将需要为集合视图和数据添加另外2个功能。 我正在使用2个数组,标题和图像名称。
  6. 这是一个示例数据数组。
    let标题= [“死侍2”,“复仇者联盟:无限战争”,“坏撒玛利亚人”,“阻止者”]
    让图片= [“死侍2”,“复仇者”,“坏撒玛利亚人”,“阻止者”]
  7. 此功能用于告诉您将有多少个单元格。
    func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int {
    返回titles.count
    }
  8. 此功能用于设置单元格内容。
    func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell {
    让单元格= featureCollectionCollectionView.dequeueReusableCell(withReuseIdentifier:“ featuredCell”,for:indexPath)为! FeaturedCollectionViewCell
    cell.imageCell.image = UIImage(名称:images [indexPath.row])
    cell.labelCell.text =标题[indexPath.row]
    返回单元
    }
  9. 您可能希望添加以下内容以使单元格看起来更好。 将这行代码添加到上面的函数中。
    cell.contentView.layer.cornerRadius = 2.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = true
    cell.layer.shadowColor = UIColor.black.cgColor
    cell.layer.shadowOffset = CGSize(宽度:0,高度:2.0)
    cell.layer.shadowRadius = 2.0
    cell.layer.shadowOpacity = 0.5
    cell.layer.masksToBounds = false
    cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds,cornerRadius:cell.contentView.layer.cornerRadius).cgPath
  10. 为了使每行只有2个像元,您需要以编程方式设置像元宽度。 以下步骤将说明如何执行此操作。
  11. 扩展视图控制器以包括“ UICollectionViewDelegateFlowLayout”。
  12. 添加以下功能。 此函数将采用集合视图的宽度并使用它来设置单元格的宽度。 *高度是为了保持图像的纵横比而计算的。 您不需要遵循它。
    func collectionView(_ collectionView:UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:IndexPath)-> CGSize {
    填充:CGFloat = 10 + 20
    让collectionViewSize = collectionView.frame.size.width —填充
    让高度= collectionViewSize / 2/128 * 192
    返回CGSize(width:collectionViewSize / 2,height:height + 17)
    }