【问题标题】:Want to load button and images in same collection view cell in swift想要在同一集合视图单元格中快速加载按钮和图像
【发布时间】:2021-07-09 10:03:23
【问题描述】:

在我的应用程序中,我必须从图库中获取图像并将其显示在集合视图中。在上图中,有一个“+”按钮,它是集合视图中的一个单元格。按下它后,它将导航到一个图像选择器,我应该能够从图库中选择一个图像。当我将任何图像添加到集合视图时,它会将图像单元格添加到图像数组的开头,并且按钮应该位于最后一个索引中。将仅对最后一个索引(+ 按钮)启用用户交互。

如何做到这一点:-

我可以将图像和按钮放在同一个单元格中,如果它是最后一个索引,那么我将显示按钮并启用用户交互?通过这样做,它将每次检查它是否是最后一个索引。

请给我任何关于如何做到这一点的建议

【问题讨论】:

    标签: swift image uicollectionview


    【解决方案1】:

    是的,它可以做到。你应该做的是,

    注意 - 在我开始之前,这里的代码未经测试,因此您必须进行更改以满足您的需要

    1. 有一个数组来保存图像,如下所示
    var imageArray: [UIImage] = [] // count is 0
    
    1. 有 2 个自定义 UICollectionViewCell,一个带有将显示图像的 UIImageView,另一个带有“UIButton. For the cell with the UIImage”,添加以下行以禁用用户交互 .
    cell.isUserInteractionEnabled = false
    cell.selectionStyle = .none
    
    1. 完成上述所有操作后(创建一个数组来保存图像,创建 2 个自定义 UICollectionViewCells),遵循 UICollectionViewDataSourceUICollectionViewDelegate 如下所示
    class ViewController: ViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
           return imageArray.count + 1 
           //Add + 1 so that there will always be atleast on cell, which will be your button cell
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            // This will show the button cell if the condition is met
            // If not, it will show the image cell
            if indexPath.row == imageArray.count - 1 || indexPath.row == 0 {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath) as! ButtonCell
                return cell
            } else {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
                // Setting image to the cell
                cell.image = imageArray[indexPath.row - 1]
                return cell
            }
        }
    
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            // This condition will make sure that the Button cell is the only one that 
            // invokes showImagePicker() when you click on any cell
            if indexPath.row == imageArray.count - 1 {
                showImagePicker()
            }
        }
    }
    

    请注意,我在项目数中添加了+1。即始终显示带有按钮的单元格,因为它始终会显示至少 1 个单元格。

    另一件事是使单元格出列,您必须添加一些条件来显示按钮单元格或图像单元格。

    1. 最后一步是使用UIImagePickerController 从图库中获取图像,将其添加到数组中,最后调用collectionview.reloadData() 方法重新加载您的收藏视图。如果你想要一个好的资源来了解 UIImagePickerController,请查看 THIS TUTORIAL 上的 Hacking with Swift

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 2021-12-11
      • 2022-06-14
      • 2016-12-06
      • 2014-10-24
      • 1970-01-01
      • 2018-08-13
      • 2021-10-06
      相关资源
      最近更新 更多