Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

UITableViewとのSwiftyな付き合い方を考えてみる

takasek
August 29, 2016

 UITableViewとのSwiftyな付き合い方を考えてみる

2016/8/29 AKIBA.swift×Swift愛好会 http://love-swift.connpass.com/event/37019/

にて発表した
「UITableViewとのSwiftyな付き合い方を考えてみる」
の登壇資料です。

デモプロジェクトはこちら
https://github.com/takasek/TableViewExample/

takasek

August 29, 2016
Tweet

More Decks by takasek

Other Decks in Programming

Transcript

  1. ૉͷ··ͩͱԿ͕ࠔΔ͔ let data = dataSource[indexPath.row] // AnyObject 4 σʔλͷܕ͕෼͔Βͳ͍ 4

    σʔλΛ໢ཏͰ͖ͳ͍ 4 σʔλΛArrayʹవΊΔऔ͔͔ͬΓ͕ͳ͍ 4 શͯͷܕΛڞ௨͢Δϓϩτίϧʹద߹ͤ͞ Δͱ͍͏ͷ΋ͳʔ… 4 ʮ͜ͷtableViewͰ࢖͏ܕʯΛ໢ཏ͍ͨ͠
  2. enum CellViewModel { case Color(UIColor) case Switch(Bool) case Slider(Float) }

    let datasource: [CellViewModel] = [ .Color(.redColor()), .Switch(true), .Slider(1.0), ] func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath ) -> UITableViewCell { switch datasource[indexPath.row] { case .Color(let color): ... case .Switch(let on): ... case .Slider(let value): ... } }
  3. func registerNib<Cell: UITableViewCell>( sameNibNameAndIdentifierAs cellClass: Cell.Type) { registerNib( UINib(nibName: "\(cellClass)",

    bundle: nil), forCellReuseIdentifier: "\(cellClass)") } func registerClass<Cell: UITableViewCell>( sameIdentifierAs cellClass: Cell.Type) { registerClass(cellClass, forCellReuseIdentifier: "\(cellClass)") } func dequeue<Cell: UITableViewCell>( sameIdentifierAs cellClass: Cell.Type, forIndexPath indexPath: NSIndexPath) -> Cell { return dequeueReusableCellWithIdentifier( "\(cellClass)", forIndexPath: indexPath ) as! Cell }
  4. ൓࿦1 func dequeue<Cell: UITableViewCell>( sameIdentifierAs cellClass: Cell.Type, forIndexPath indexPath: NSIndexPath

    ) -> Cell { let identifier = "\(cellClass)" return dequeueReusableCellWithIdentifier( identifier, forIndexPath: indexPath ) as! Cell } ʮ as! Cell ͸ཚ๫͗ͩ͢Ζ!?ʯ
  5. ͔͠͠ɺ 4 identifier͕register͞Ε͍ͯͳ͚Ε͹ɺΩϟετ͢Δલʹ UIKit࣌఺ͰΫϥογϡ͢ΔʢiOS6Ҏ߱ʣ 4 register͞Εͨܕ͸identifierͱಉҰͩͱอূͰ͖Δ 4 identifier͸ಛఆͷCellͷܕʹඥ෇͍͍ͯΔ 4 identifier͕ผͷܕ͕ඥ෇͍͍ͯͨͱͨ͠ΒɺͦΕ͸

    identifierͷࢦఆ͕ෆຯ͍ ͱߟ͑Ε͹ɺ ! Ͱ໰୊͋Γ·ͤΜ dequeueReusableCellWithIdentifier( identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell // newer dequeue method // guarantees a cell is returned and resized properly, // assuming identifier is registered
  6. ·ͱΊ ᶃTableView͕σʔλʹؔ৺͕͋Δέʔε ɹ= indexPathͰಛఆ 4 σʔλͷछྨΛ஋͖ͭEnumͰ໢ཏˍܕ҆શʹऔΓѻ͏ ᶄTableView͕Cellͷ࣮ମʹؔ৺͕͋Δέʔε ɹ= reuseIdentifierͰಛఆ 4

    reuseIdentifier = Class໊ ͱ͍͏ϧʔϧΛಋೖ͠ɺ ڧ੍ ΩϟετͰແཧ໼ཧܕ҆શʹऔΓѻ͏ 4 ࣮ࡍ͸reuseIdentifier:Class͸ଟର1ͳͷͰɺOptionalͰ identifierΛࢦఆՄೳʹ