Day20 - collectionViewCell动画

最终效果

day20.gif

时间过得挺快的!一下子就写到了Day20了

在开始之前先了解一个东西:
guard:guard 语句,类似于 if 语句,基于布尔值表达式来执行语句。使用 guard 语句来要求一个条件必须是真才能执行 guard 之后的语句。与 if 语句不同, guard 语句总是有一个 else 分句—— else 分句里的代码会在条件不为真的时候执行。

代码说明:
    var name : String? = "小明"
    
    func printName(){
//        if (name != nil) {
//            NSLog(@"%@",name);
//        }else{
//            print("名字都没有,你搞什么呢")
//        }
        
        // Swift1
//        if name != nil {
//            print(name)
//        }
//        else{
//            print("名字都没有,你搞什么呢?")
//        }
        
        // Swift2
//        if let xiaoming = name {
//            print(xiaoming)
//        }
//        else{
//            print("名字都没有,你搞什么呢?")
//        }
        
        // guard - 单个参数,单个条件
        // 结果是输出小明
//        guard let xiaoming = name else {
//            print("名字都没有,你搞什么呢?")
//            return
//        }
//        
//        print(xiaoming)
//        
//        // guard - 单个参数,多个条件
//        //结果是输出 名字都没有,你搞什么呢?
//        guard let xiaoming1 = name where name == "小2明" else {
//            print("名字都没有,你搞什么呢?")
//            return
//        }
//        print(xiaoming1)
        
        // guard - 多个参数
        //结果 小红、小明 这里参数必须都满足,否则就会执行 else {... return}
        let hong : String? = "小红"
        guard let xiaohong = hong , xiaoming2 = name else {
            print("调价不满足")
            return
        }
        
        print(xiaohong)
        print(xiaoming2)
    }
   

<br />
在了解了上面的知识后,就开始完成这个效果吧

1、UI布局

之前很多次都是使用了storyboard,这次使用代码
<br />
1.1 先创建一个collectionview

var collectionView: UICollectionView! = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 260 )
        let coll = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: flowLayout)
        coll.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        return coll
    }()

<br />

1.2 使用xib创建Cell


填入名字,创建XIB

<br />
1.3 设置Xib内容


设置如下效果

到这里位置,UI部分已经完成了,接下来就是代码实现

<br />

2、代码实现

2.1 创建一个模型,加载图片 类名:AnimationCellModel

import UIKit

struct AnimationCellModel {
    
    let imagePath :String
    
    init(imagePath : String?){
        self.imagePath = imagePath ?? ""
    }
    
}

<br />
2.2 创建一个数组,加载模型 类名:AnimationImageCollection

import UIKit

struct AnimationImageCollection {
    private let imagePaths = ["1","2","3","4","5"]
    var images : [AnimationCellModel]
    
    init(){
        images = imagePaths.map { AnimationCellModel(imagePath: $0) }
    }
}

<br />
2.3 在刚才创建的cell中把背景图片,和button,拖入到文件中,实现下面方法,都有注释

import UIKit

class AnimationCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var backImage: UIImageView!
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    
    /// 定义一个闭包
    var backButtonTapped : (() -> ())?
    
    func prepareCell(viewModel : AnimationCellModel){
        // 设置背景图片
        backImage.image = UIImage(named: viewModel.imagePath)
        // 设置按钮默认隐藏
        backButton.hidden = true
        // 为按钮添加点击事件
        addTapEventHandler()
    }
    
    // 当选中cell的时候调用方法
    func handleCellSelected() -> Void {
        backButton.hidden = false
        self.superview?.bringSubviewToFront(self)
    }
    
    // 按钮的点击事件
    private func addTapEventHandler(){
        backButton.addTarget(self, action: #selector(AnimationCollectionViewCell.backButtonClick), forControlEvents: .TouchUpInside)
    }
    
    @objc private func backButtonClick(){
        
        guard let back = backButtonTapped else {
            print("闭包是空的")
            return
        }
        
        back()
        
        // if 的写法
        /*
         if let back = backButtonTapped{
         back()
         }
         else{
         print("闭包是空的")
         }
         */
    }
}

<br />
<br />
2.4 通过上面的方法,我们已经设置了好数据源,并且设置好了cell,接下来把collectionview加载到ViewController中,然后在设置代理,实现代理,监听点击,然后开始动画

//
//  ViewController.swift
//  CollectionViewAnimation
//
//  Created by ios on 16/9/27.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

// MARK: - category方法
extension Array {
    //判断是否在下标区间内,在就返回值 否则返回空
    func safeIndex(i: Int) -> Element? {
        return i < self.count && i >= 0 ? self[i] : nil
    }
}

//Xib
private struct Storyboard{
    static let CellIdentifier = String(AnimationCollectionViewCell)
    static let NibName = String(AnimationCollectionViewCell)
}

//动画
private struct Constans {
    static let Duration : Double = 0.5
    static let Delay : Double = 0.0
    static let SpringDamping : CGFloat = 1.0
    static let SpringVelocity : CGFloat = 1.0
}

class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{
    //数据源
    private var imageCollection = AnimationImageCollection()
    
    //懒加载collectionview
    private lazy var collectionView: UICollectionView! = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 260 )
        let coll = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: flowLayout)
        coll.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        return coll
    }()
    
    // 加载CollectionView
    override func viewDidLoad() {
        super.viewDidLoad()
        //register 提前注册
        collectionView.registerNib(UINib(nibName: Storyboard.NibName, bundle: nil), forCellWithReuseIdentifier: Storyboard.CellIdentifier)
        
        //设置代理
        collectionView.delegate = self
        collectionView.dataSource = self
        
        //加载View
        view.addSubview(collectionView)
    }
    
    // 设置系统状态栏样式
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }

}

// MARK: - 这里是Collectionview的代理 Datasource delegate
extension ViewController{

    // 返回有多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageCollection.images.count ?? 0
    }
    
    // 设置每个cell的样式
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //这里要满足两个条件
        guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as? AnimationCollectionViewCell, viewModel = imageCollection.images.safeIndex(indexPath.row) else {
            return UICollectionViewCell()
        }
        
        cell.prepareCell(viewModel)
        
        return cell
    }
    
    // cell 被点击是调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? AnimationCollectionViewCell else{
            print("拿不到Cell")
            return
        }
        
        //调用动画方法
        cellAnimationWith(cell, collectionView: collectionView)
    }
    
    private func cellAnimationWith(cell : AnimationCollectionViewCell,collectionView : UICollectionView){
        // 设置为选中状态
        cell.handleCellSelected()
        
        //保存闭包代码
        cell.backButtonTapped = {
            guard let indexPaths = self.collectionView.indexPathsForSelectedItems() else{
                return
            }
            collectionView.scrollEnabled  = true
            collectionView.reloadItemsAtIndexPaths(indexPaths)
        }
        // 设置动画
        let animation : () -> () = {
            //设置大小
            cell.frame = collectionView.bounds
        }
        
        //动画结束又可以滑动了
        let completion : (fnished : Bool) -> () = { _ in
            collectionView.scrollEnabled = false
        }
        //开始动画
        UIView.animateWithDuration(Constans.Duration, delay: Constans.Delay, usingSpringWithDamping: Constans.SpringDamping, initialSpringVelocity: Constans.SpringVelocity, options: [], animations: animation, completion: completion)
    }
    
}




本文Demo - CollectionViewAnimation

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • 离2017年全国高考不到20个小时了。我独坐桌前,想着给即将奔赴考场的学子们一些更好的方法,来帮助他们轻松应对高考...
    清浅第五空间阅读 873评论 1 4
  • 梦想不难实现,却仍有大多人失去了他的梦想,可能会有少数外界因素,但最为重要的是自己为梦想做了什么,最简单也最难的便...
    枫酿阅读 253评论 0 0