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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容

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