swift 面向协议点击显示大图--带缩放功能

直接上代码

首先定义一个显示大图的协议

protocol ShowImageProtocol {}

然后添加协议extension---
1.第一个是不带动画的直接模态显示出大图控制器界面
2.第二个是带动画的协议扩展,类似于微信朋友圈显示大图,但是此时需要显示的图片所在的控制器准守UIViewControllerTransitioningDelegate协议;并且为了使动画开始frame是从所点击的imageView展开显示的,所以需要外界传入一个imageView,用来获取初始frame

extension ShowImageProtocol where Self: UIViewController {
    /**
     不带动画的显示大图
     
     - parameter dataSource:   数据源
     - parameter currentIndex: 第几个
     */
    func showImages(with dataSource: [String], currentIndex: Int) {
        
        guard dataSource.count - 1 >= currentIndex else {
            return
        }
        let vc = ShowImagesController(dataSource: dataSource, currentIndex: currentIndex)
        vc.modalTransitionStyle = .CrossDissolve
        presentViewController(vc, animated: true, completion: nil)
    }
}

extension ShowImageProtocol where Self: UIViewController, Self: UIViewControllerTransitioningDelegate {
    /**
     带动画的显示大图---必须遵循UIViewControllerTransitioningDelegate
     
     - parameter dataSource:   数据源
     - parameter currentIndex: 第几个
     - parameter imageView:    要显示的imageView,主要是为了获取frame
     */
    func showImages(with dataSource: [String], currentIndex: Int, delegate: ModalAnimationDelegate?) {
        guard let delegate = delegate else {
            fatalError("does not have delegate")
        }
        guard dataSource.count - 1 >= currentIndex else {
            return
        }
        let vc = ShowImagesController(dataSource: dataSource, currentIndex: currentIndex)
        vc.transitioningDelegate = delegate
        vc.modalPresentationStyle = .Custom
        presentViewController(vc, animated: true, completion: nil)
    }
}

外界调用时,需要首先准守ShowImageProtocol协议
1.不带动画的直接调用第一个方法即可

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PicCollectionViewCell else { return }
     showImages(with: viewModel.dataSource, currentIndex: indexPath.item)
}

2.带动画的还需要准守UIViewControllerTransitioningDelegate协议。同时控制器设置属性

private var delegate: ModalAnimationDelegate?

然后,在需要显示大图的地方,先把delegate置为nil,再创建delegate---因为此方法需要一个imageView属性,所以最好把属性设置为可选,然后先置为nil,再创建delegate

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PicCollectionViewCell else { return }
        delegate = nil
        delegate = ModalAnimationDelegate(originalView: cell.picV)
            showImages(with: viewModel.dataSource, currentIndex: indexPath.item, delegate: delegate)
    }

同时

在这里有一个地方需要特别注意的---那就是显示大图的控制器collectionviewcell之间有间距的设置方法:
把collectionView和cell的宽设置为屏宽加固定的间距并且cell之间间距为0,同时开始开启pagingEnabled = true,当然cell上的scrollview需距离到contentView右侧边距为我们设置的间距大小。

/// 滚动时,cell所显示的间距大小
private let cellMargin: CGFloat = 20
//这个是显示大图的控制器vc的初始化类方法
convenience init(dataSource: [String], currentIndex: Int) {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width + cellMargin, height: UIScreen.mainScreen().bounds.height)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .Horizontal
        self.init(collectionViewLayout: layout)
        self.dataSource = dataSource
        self.currentIndex = currentIndex
    }

然后在viewDidLoad()里面设置collectionview的frame

collectionView?.frame = UIScreen.mainScreen().bounds
        collectionView?.frame.size.width = UIScreen.mainScreen().bounds.size.width + cellMargin
        
        collectionView?.alwaysBounceHorizontal = true
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        
        collectionView?.registerClass(PicuterCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex, inSection: 0), atScrollPosition: .Left, animated: false)

同时为了大图需要带有缩放功能,我们需要在cell上放置一个scrollview,然后scrollview上再放置UIimageview。这里没有使用第三方布局,而是使用代码约束控件

private func setUpUI() {
        contentView.addSubview(scrollView)
        // 关闭autoresizing 不关闭否则程序崩溃
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        let topConstraint = NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 0)
        let leftConstraint = NSLayoutConstraint(item: scrollView, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: scrollView, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -cellMargin)
        contentView.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint])

        scrollView.minimumZoomScale = 1
        scrollView.maximumZoomScale = 3
        scrollView.delegate = self
        
        scrollView.addSubview(picV)
        picV.contentMode = .ScaleAspectFit
        
        picV.translatesAutoresizingMaskIntoConstraints = false
        let centerXCon = NSLayoutConstraint(item: picV, attribute: .CenterX, relatedBy: .Equal, toItem: scrollView, attribute: .CenterX, multiplier: 1, constant: 0)
        let centerYCon = NSLayoutConstraint(item: picV, attribute: .CenterY, relatedBy: .Equal, toItem: scrollView, attribute: .CenterY, multiplier: 1, constant: 0)
        
        let leftCon = NSLayoutConstraint(item: picV, attribute: .Left, relatedBy: .Equal, toItem: scrollView, attribute: .Left, multiplier: 1, constant: 0)
        let rightCon = NSLayoutConstraint(item: picV, attribute: .Right, relatedBy: .Equal, toItem: scrollView, attribute: .Right, multiplier: 1, constant: 0)
        
        let heightCon = NSLayoutConstraint(item: picV, attribute: .Height, relatedBy: .Equal, toItem: scrollView, attribute: .Height, multiplier: 1, constant: 0)

        scrollView.addConstraints([heightCon, leftCon, rightCon, centerYCon, centerXCon])
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        picV.userInteractionEnabled = true
        picV.addGestureRecognizer(tap)
    }

然后,我们需要在滑动到下一个cell时,使上一个cell里面的图像复原,这里需要用到collectionview的代理方法--cell滑动消失时触发

override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        guard let cell = cell as? PicuterCell else {
            return
        }
        cell.reset()
    }

//这个是cell里的方法,设置scrollview的缩放为1.0
func reset() {
        scrollView.setZoomScale(1.0, animated: false)
    }

demo地址:https://github.com/guijie20140501/ShowBigImage.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,251评论 4 61
  • 阿明和我是初中同学。上学时他学习非常努力认真,每次考试稳坐班里的第一把交椅,是个十足的学霸。 这两日他到我的城市出...
    商小茉阅读 1,303评论 0 5
  • 接受颠覆 现在出来一些事情会颠复我们的一些正常思路,在貌似不可思议的思维后他就摆在你面前,让你接受他是如而且他...
    易凡风顺阅读 232评论 0 0
  • 小时候妈妈常说,女孩子要学会笑。大概看不过我经常和弟弟生气吧。还是个青少年时,有好多理由开心和不开心,说来就来的情...
    买基金的Gargamel阅读 179评论 0 0