UIKit框架(四) —— UICollectionViewCell的扩张效果的实现(二)

版本记录

版本号 时间
V1.0 2018.10.31 星期三

前言

iOS中有关视图控件用户能看到的都在UIKit框架里面,用户交互也是通过UIKit进行的。感兴趣的参考上面几篇文章。
1. UIKit框架(一) —— UIKit动力学和移动效果(一)
2. UIKit框架(二) —— UIKit动力学和移动效果(二)
3. UIKit框架(三) —— UICollectionViewCell的扩张效果的实现(一)

源码

1. Swift

首先看一下工程组织结构

看一下sb中的内容

1. InspirationsViewController.swift
import UIKit

class InspirationsViewController: UICollectionViewController {
  let inspirations = Inspiration.allInspirations()
  
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return UIStatusBarStyle.lightContent
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let patternImage = UIImage(named: "Pattern") {
      view.backgroundColor = UIColor(patternImage: patternImage)
    }
    collectionView?.backgroundColor = .clear
    collectionView?.decelerationRate = .fast
  }
}

extension InspirationsViewController {
  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return inspirations.count
  }
  
  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(
      withReuseIdentifier: InspirationCell.reuseIdentifier, for: indexPath)
      as? InspirationCell else {
        return UICollectionViewCell()
    }
    cell.inspiration = inspirations[indexPath.item]
    return cell
  }
}
2. UIColor+Palette.swift
import UIKit

extension UIColor {
  class func colorFromRGB(_ r: Int, g: Int, b: Int) -> UIColor {
    return UIColor(red: CGFloat(Float(r) / 255), green: CGFloat(Float(g) / 255), blue: CGFloat(Float(b) / 255), alpha: 1)
  }
  
  class func palette() -> [UIColor] {
    let palette = [
      UIColor.colorFromRGB(85, g: 0, b: 255),
      UIColor.colorFromRGB(170, g: 0, b: 170),
      UIColor.colorFromRGB(85, g: 170, b: 85),
      UIColor.colorFromRGB(0, g: 85, b: 0),
      UIColor.colorFromRGB(255, g: 170, b: 0),
      UIColor.colorFromRGB(255, g: 255, b: 0),
      UIColor.colorFromRGB(255, g: 85, b: 0),
      UIColor.colorFromRGB(0, g: 85, b: 85),
      UIColor.colorFromRGB(0, g: 85, b: 255),
      UIColor.colorFromRGB(170, g: 170, b: 255),
      UIColor.colorFromRGB(85, g: 0, b: 0),
      UIColor.colorFromRGB(170, g: 85, b: 85),
      UIColor.colorFromRGB(170, g: 255, b: 0),
      UIColor.colorFromRGB(85, g: 170, b: 255),
      UIColor.colorFromRGB(0, g: 170, b: 170)
    ]
    return palette
  }
}
3. UIImage+Decompression.swift
import UIKit

extension UIImage {
  var decompressedImage: UIImage {
    UIGraphicsBeginImageContextWithOptions(size, true, 0)
    draw(at: CGPoint.zero)
    guard let decompressedImage = UIGraphicsGetImageFromCurrentImageContext() else {
      return UIImage()
    }
    UIGraphicsEndImageContext()
    return decompressedImage
  }
}
4. UltravisualLayout.swift
import UIKit

// The heights are declared as constants outside of the class so they can be easily referenced elsewhere 
struct UltravisualLayoutConstants {
  struct Cell {
    // The height of the non-featured cell 
    static let standardHeight: CGFloat = 100
    // The height of the first visible cell 
    static let featuredHeight: CGFloat = 280
  }
}

// MARK: Properties and Variables

class UltravisualLayout: UICollectionViewLayout {
  // The amount the user needs to scroll before the featured cell changes 
  let dragOffset: CGFloat = 180.0
  
  var cache: [UICollectionViewLayoutAttributes] = []
  
  // Returns the item index of the currently featured cell 
  var featuredItemIndex: Int {
    // Use max to make sure the featureItemIndex is never < 0 
    return max(0, Int(collectionView!.contentOffset.y / dragOffset))
  }
  
  // Returns a value between 0 and 1 that represents how close the next cell is to becoming the featured cell 
  var nextItemPercentageOffset: CGFloat {
    return (collectionView!.contentOffset.y / dragOffset) - CGFloat(featuredItemIndex)
  }
  
  // Returns the width of the collection view 
  var width: CGFloat {
    return collectionView!.bounds.width
  }
  
  // Returns the height of the collection view 
  var height: CGFloat {
    return collectionView!.bounds.height
  }
  
  // Returns the number of items in the collection view 
  var numberOfItems: Int {
    return collectionView!.numberOfItems(inSection: 0)
  }
}

// MARK: UICollectionViewLayout

extension UltravisualLayout {
  // Return the size of all the content in the collection view 
  override var collectionViewContentSize : CGSize {
    let contentHeight = (CGFloat(numberOfItems) * dragOffset) + (height - dragOffset)
    return CGSize(width: width, height: contentHeight)
  }
  
  override func prepare() {
    cache.removeAll(keepingCapacity: false)
    
    let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
    let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
  
    var frame = CGRect.zero
    var y: CGFloat = 0
    
    for item in 0..<numberOfItems {
      let indexPath = IndexPath(item: item, section: 0)
      let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
      // Important because each cell has to slide over the top of the previous one 
      attributes.zIndex = item
      // Initially set the height of the cell to the standard height 
      var height = standardHeight
      if indexPath.item == featuredItemIndex {
        // The featured cell 
        let yOffset = standardHeight * nextItemPercentageOffset
        y = collectionView!.contentOffset.y - yOffset
        height = featuredHeight
      } else if indexPath.item == (featuredItemIndex + 1) && indexPath.item != numberOfItems {
        // The cell directly below the featured cell, which grows as the user scrolls 
        let maxY = y + standardHeight
        height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0)
        y = maxY - height
      }
      frame = CGRect(x: 0, y: y, width: width, height: height)
      attributes.frame = frame
      cache.append(attributes)
      y = frame.maxY
    }
  }
  
  // Return all attributes in the cache whose frame intersects with the rect passed to the method 
  override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var layoutAttributes: [UICollectionViewLayoutAttributes] = []
    for attributes in cache {
      if attributes.frame.intersects(rect) {
        layoutAttributes.append(attributes)
      }
    }
    return layoutAttributes
  }
  
  // Return the content offset of the nearest cell which achieves the nice snapping effect, similar to a paged UIScrollView 
  override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
    let itemIndex = round(proposedContentOffset.y / dragOffset)
    let yOffset = itemIndex * dragOffset
    return CGPoint(x: 0, y: yOffset)
  }
  
  // Return true so that the layout is continuously invalidated as the user scrolls 
  override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
    return true
  }
}
5. Inspiration.swift
import UIKit

class Inspiration: Session {
  class func allInspirations() -> [Inspiration] {
    var inspirations: [Inspiration] = []
    guard let URL = Bundle.main.url(forResource: "Inspirations", withExtension: "plist"),
      let tutorialsFromPlist = NSArray(contentsOf: URL) else {
        return inspirations
    }
    for dictionary in tutorialsFromPlist {
      let inspiration = Inspiration(dictionary: dictionary as! NSDictionary)
      inspirations.append(inspiration)
    }
    return inspirations
  }
}
6. Session.swift
import UIKit

class Session {
  var title: String
  var speaker: String
  var room: String
  var time: String
  var backgroundImage: UIImage
  
  var roomAndTime: String {
    get {
      return "\(time) • \(room)"
    }
  }
  
  init(title: String, speaker: String, room: String, time: String, backgroundImage: UIImage) {
    self.title = title
    self.speaker = speaker
    self.room = room
    self.time = time
    self.backgroundImage = backgroundImage
  }
  
  convenience init(dictionary: NSDictionary) {
    let title = dictionary["Title"] as? String
    let speaker = dictionary["Speaker"] as? String
    let room = dictionary["Room"] as? String
    let time = dictionary["Time"] as? String
    let backgroundName = dictionary["Background"] as? String
    let backgroundImage = UIImage(named: backgroundName!)
    self.init(title: title!, speaker: speaker!, room: room!, time: time!, backgroundImage: backgroundImage!.decompressedImage)
  }
}
7. InspirationCell.swift
import UIKit

class InspirationCell: UICollectionViewCell {
  static let reuseIdentifier = String(describing: InspirationCell.self)
  
  @IBOutlet private weak var imageView: UIImageView!
  @IBOutlet private weak var imageCoverView: UIView!
  @IBOutlet private weak var titleLabel: UILabel!
  @IBOutlet private weak var timeAndRoomLabel: UILabel!
  @IBOutlet private weak var speakerLabel: UILabel!
  
  var inspiration: Inspiration? {
    didSet {
      if let inspiration = inspiration {
        imageView.image = inspiration.backgroundImage
        titleLabel.text = inspiration.title
        timeAndRoomLabel.text = inspiration.roomAndTime
        speakerLabel.text = inspiration.speaker
      }
    }
  }
  
  override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
    super.apply(layoutAttributes)
    
    let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
    let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
    
    let delta = 1 - ((featuredHeight - frame.height) / (featuredHeight - standardHeight))
    
    let minAlpha: CGFloat = 0.3
    let maxAlpha: CGFloat = 0.75
    
    imageCoverView.alpha = maxAlpha - (delta * (maxAlpha - minAlpha))
    
    let scale = max(delta, 0.5)
    titleLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
    
    timeAndRoomLabel.alpha = delta
    speakerLabel.alpha = delta
  }
}

后记

本篇主要讲述了UICollectionViewCell的扩张效果的实现,感兴趣的给个赞或者关注~~~

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

推荐阅读更多精彩内容