如何向我的 UICollectionView 添加额外的静态单元格? [英] How to add an extra static cell to my UICollectionView?

查看:22
本文介绍了如何向我的 UICollectionView 添加额外的静态单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 UICollectionView 中显示了一组照片.我仍然想添加的唯一一件事是一个额外的静态单元,它应该让用户有可能打开相机.我使用了 if-else 语句来检测索引.不幸的是,控制台给了我一个索引错误.

I have an array of photos that I currently display in a UICollectionView. The only thing I still want to add is an extra static cell that should give the user the possibility to open the camera. I used an if-else statement to detect the index. Unfortunately, the console gives me an out of index error.

准确地说:我希望这个静态单元格位于左上角,然后是我的图像数组.我是否必须添加两个部分,还是应该注册另一个自定义单元格来完成此操作?截至目前,我可以看到我的额外单元格,但在点击(超出索引)时它不起作用.

To be precise: I want this static cell to be in the top left corner, followed by my array of images. Do I have to add two sections, or should I register another custom cell to accomplish this? As of now I can see my extra cell, but it's not working when tapped (out of index).

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count + 1
}

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoId, for: indexPath) as! PhotosCollectionViewCell

    if indexPath.row == imageArray.count {
        cell.backgroundColor = UIColor.lightGray
        cell.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(tappedCamera)))
    } else {
        cell.imageView.image = imageArray[indexPath.item]
        cell.imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(tappedPhoto)))
    }

    return cell
}

更新代码(解决方案)

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count + 1
}

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

    if indexPath.row == 0 {
        let cameraCell = collectionView.dequeueReusableCell(withReuseIdentifier: cameraId, for: indexPath) as! CameraCollectionViewCell
        return cameraCell
    }

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tappedPhoto))
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoId, for: indexPath) as! PhotoCollectionViewCell

    cell.imageView.image = imageArray[indexPath.row - 1]
    cell.imageView.addGestureRecognizer(tapGesture)

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        print("Camera")
    } 
}

var startingFrame: CGRect?
var blackBackGroundView: UIView?
var selectedImageFromPicker: UIImage?
var selectedImageCompressed: UIImage?

func tappedPhoto(sender: UIGestureRecognizer) {
    if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

        let imageView = self.collectionView?.cellForItem(at: indexPath)

        startingFrame = imageView?.superview?.convert((imageView?.frame)!, to: nil)

        let zoomingImageView = UIImageView(frame: startingFrame!)
        zoomingImageView.image = imageArray[indexPath.row - 1]
        zoomingImageView.isUserInteractionEnabled = true
        zoomingImageView.contentMode = .scaleAspectFill
        zoomingImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomOut)))

        if let keyWindow = UIApplication.shared.keyWindow {
            blackBackGroundView = UIView(frame: keyWindow.frame)
            blackBackGroundView?.backgroundColor = UIColor.black
            blackBackGroundView?.alpha = 0

            keyWindow.addSubview(blackBackGroundView!)
            keyWindow.addSubview(chooseLabel)
            keyWindow.addSubview(zoomingImageView)

            // Set selected image and compress
            selectedImageFromPicker = imageArray[indexPath.row - 1]
            selectedImageCompressed = selectedImageFromPicker?.resized(withPercentage: 0.1)

            chooseLabel.rightAnchor.constraint(equalTo: keyWindow.rightAnchor, constant: -25).isActive = true
            chooseLabel.bottomAnchor.constraint(equalTo: keyWindow.bottomAnchor, constant: -25).isActive = true

            UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

                self.blackBackGroundView?.alpha = 1
                self.chooseLabel.alpha = 1

                let height = self.startingFrame!.height / self.startingFrame!.width * keyWindow.frame.width

                zoomingImageView.frame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: height)

                zoomingImageView.center = keyWindow.center

                }, completion: {(completed) in
                    // Do nothing
            })
        }
    }
}

推荐答案

我是否必须添加两个部分,或者我应该注册另一个自定义单元来完成这个?

Do I have to add two sections, or should I register another custom cell to accomplish this?

在您的情况下,只需在集合的开头添加一个单元格就足够公平了,无需对其进行多节.

In your case, just adding one cell at the beginning of the collection should be fair enough, there is no need to multi-section it.

您的方法应按如下方式实现:

Your methods should be implemented as follows:

1- numberOfItemsInSection 方法:应该是:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count + 1
}

2- cellForItemAt 方法:取决于第一个单元格,如果它应该是不同的单元格:

2- cellForItemAt method: depends on the first cell, if it should be a different cell:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // first row
    if indexPath.row == 0 {
        let cameraCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cameraCell-ID", for: indexPath)

        // setup the cell...

        return cameraCell
    }

    let defaultCell = collectionView.dequeueReusableCell(withReuseIdentifier: "defaultCell-ID", for: indexPath)

    // setup default cell...

    return defaultCell
}

或者,如果您希望它是同一个单元格,但有一些版本:

Or, if you want it to be the same cell, but with some editions:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-ID", for: indexPath)

    // first row
    if indexPath.row == 0 {
        // setup the cell as cemera cell...
    } else {
        // setup the cell as default cell...
    }

    return cell
}

实际上,不需要为每个单元格添加UITapGestureRecognizer,你所要做的就是实现collection View(_: did Select Item At: )委托方法:

Actually, there is no need to add UITapGestureRecognizer for each cell, all you have to do is to implement collection​View(_:​did​Select​Item​At:​) delegate method:

告诉委托指定索引路径的项目是已选中.

Tells the delegate that the item at the specified index path was selected.

3- didSelectItemAt 方法:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.row == 0 { // camera cell
        // handle tapping the camera cell
    } else { // default cells
        // handle tapping the default cell

        // don't forget that:
        // getting the first element in 'imageArray' should be imageArray[indexPath.row - 1]
    }
}

希望这有帮助.

这篇关于如何向我的 UICollectionView 添加额外的静态单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆