UIKit框架(四) —— UICollectionViewCell的擴(kuò)張效果的實(shí)現(xiàn)(二)

版本記錄

版本號 時(shí)間
V1.0 2018.10.31 星期三

前言

iOS中有關(guān)視圖控件用戶能看到的都在UIKit框架里面戈钢,用戶交互也是通過UIKit進(jìn)行的馆蠕。感興趣的參考上面幾篇文章期升。
1. UIKit框架(一) —— UIKit動(dòng)力學(xué)和移動(dòng)效果(一)
2. UIKit框架(二) —— UIKit動(dòng)力學(xué)和移動(dòng)效果(二)
3. UIKit框架(三) —— UICollectionViewCell的擴(kuò)張效果的實(shí)現(xiàn)(一)

源碼

1. Swift

首先看一下工程組織結(jié)構(gòu)

看一下sb中的內(nèi)容

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的擴(kuò)張效果的實(shí)現(xiàn),感興趣的給個(gè)贊或者關(guān)注~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末互躬,一起剝皮案震驚了整個(gè)濱河市播赁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吼渡,老刑警劉巖容为,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異寺酪,居然都是意外死亡坎背,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進(jìn)店門寄雀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來得滤,“玉大人,你說我怎么就攤上這事盒犹《” “怎么了眨业?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長沮协。 經(jīng)常有香客問我坛猪,道長,這世上最難降的妖魔是什么皂股? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任墅茉,我火速辦了婚禮,結(jié)果婚禮上呜呐,老公的妹妹穿的比我還像新娘就斤。我一直安慰自己,他們只是感情好蘑辑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布洋机。 她就那樣靜靜地躺著,像睡著了一般洋魂。 火紅的嫁衣襯著肌膚如雪绷旗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天副砍,我揣著相機(jī)與錄音衔肢,去河邊找鬼。 笑死豁翎,一個(gè)胖子當(dāng)著我的面吹牛角骤,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播心剥,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼邦尊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了优烧?” 一聲冷哼從身側(cè)響起蝉揍,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎畦娄,沒想到半個(gè)月后又沾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡纷责,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年捍掺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了撼短。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片再膳。...
    茶點(diǎn)故事閱讀 40,090評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖曲横,靈堂內(nèi)的尸體忽然破棺而出喂柒,到底是詐尸還是另有隱情不瓶,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布灾杰,位于F島的核電站蚊丐,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏艳吠。R本人自食惡果不足惜麦备,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望昭娩。 院中可真熱鬧凛篙,春花似錦、人聲如沸栏渺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽磕诊。三九已至填物,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間霎终,已是汗流浹背滞磺。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留莱褒,地道東北人雁刷。 一個(gè)月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像保礼,于是被迫代替她去往敵國和親沛励。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容