首页 > 解决方案 > 如何实现小视图变成全屏视图的效果?类似于 Snapchat 从集合视图到内容视图的转换

问题描述

我包含了一个 GIF 以更好地展示我想要实现的目标:

在此处输入图像描述

我怎样才能做到这一点?

一些想法:

注意:我只需要在一个地方创建这种功能,所以如果我要使用 collectionView 它总是只有 1 个 Cell。

另外,另一个例子,可能是我想要实现的一个更好的例子是苹果照片应用程序。在其中,您有一个图像集合视图,当您点击一个图像时,它会扩展为全屏,但作为 VC。我还想实现在照片应用程序中向下滑动时获得的那种自由感觉。

标签: iosswift

解决方案


如果您想使用集合视图的单元格来执行此操作。

//
//  ViewController.swift
//  test
//
//  Created by Sergio Rodríguez Rama on 22/04/2019.
//  Copyright © 2019 Sergio Rodríguez Rama. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    private var smallView: UIView?
    private var smallFrame: CGRect?
    private var bigFrame: CGRect?

    @objc private func viewTapped() {
        UIView.animate(withDuration: 1, animations: { [weak self] in
            guard let smallFrame = self?.smallFrame else { return }
            self?.smallView?.frame = smallFrame
        }) { [weak self] _ in
            self?.smallView?.removeFromSuperview()
            self?.collectionView.isUserInteractionEnabled = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        bigFrame = view.frame
        collectionView.delegate = self
        collectionView.dataSource = self
    }
}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) else { return }
        smallFrame = collectionView.convert(cell.frame, to: view)
        smallView = cell.copyView()
        guard let smallFrame = smallFrame, let smallView = smallView else { return }
        smallView.frame = smallFrame
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        smallView.addGestureRecognizer(tapGestureRecognizer)
        view.addSubview(smallView)
        collectionView.isUserInteractionEnabled = false
        UIView.animate(withDuration: 1, animations: { [weak self] in
            guard let frame = self?.bigFrame else { return }
            self?.smallView?.frame = frame
        })
    }
}

extension UIView
{
    func copyView<T: UIView>() -> T {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
    }
}

推荐阅读