Skip to content

Instantly share code, notes, and snippets.

@gitbricho
Last active July 21, 2016 08:52
Show Gist options
  • Save gitbricho/856e0489ca75796447cdcfd4895fa304 to your computer and use it in GitHub Desktop.
Save gitbricho/856e0489ca75796447cdcfd4895fa304 to your computer and use it in GitHub Desktop.
iOS Table View
import UIKit
@UIApplicationMain
class AppDelegate: NSObject, UIApplicationDelegate, UISplitViewControllerDelegate {
// MARK: プロパティ
var window: UIWindow?
// MARK: UIApplicationDelegate
// アプリの起動準備ができたことをデリゲートに知らせる
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool {
// --- ここで起動後のカスマイズ処理を行う -----
// ウィンドウのルートビューコントローラ(スプリットビューコントローラ)を取得
let splitViewController = window!.rootViewController as! UISplitViewController
// スプリットビューコントローラのデリゲートを設定
splitViewController.delegate = self
splitViewController.preferredDisplayMode = .allVisible
return true
}
// MARK: UISplitViewControllerDelegate
// スプリットビューコントローラのアクション発生時に適用すべき表示モードを返す
func targetDisplayModeForAction(
in splitViewController: UISplitViewController)
-> UISplitViewControllerDisplayMode {
return .allVisible
}
}
import UIKit
/*:
メニュー・テーブルビュー・コントローラ.
テーブルビュー:(コンテント:静的セル, スタイル :プレーン,セクション数:1)
セクション1:(行数: 4 (cell01 ... cell04)
セルの選択時にセグエを起動
cell01...04 -> show detail Table01...04
*/
class MasterViewController: UITableViewController {
@IBOutlet weak var cell01: UITableViewCell!
@IBOutlet weak var cell02: UITableViewCell!
@IBOutlet weak var cell03: UITableViewCell!
@IBOutlet weak var cell04: UITableViewCell!
let RED_START_COLOR: CGFloat = 0.15
let RED_INC_COLOR: CGFloat = 0.11
let SELECTEDCOLOR = UIColor(
red: 0.6, green: 0.3, blue: 0.4, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
var redCol: CGFloat = RED_START_COLOR
let redInc: CGFloat = RED_INC_COLOR
redCol = setCellAttr(
cell01, redCol: redCol, redInc: redInc)
redCol = setCellAttr(
cell02, redCol: redCol, redInc: redInc)
redCol = setCellAttr(
cell03, redCol: redCol, redInc: redInc)
redCol = setCellAttr(
cell04, redCol: redCol, redInc: redInc)
}
func setCellAttr(
_ cell: UITableViewCell, redCol: CGFloat, redInc: CGFloat) -> CGFloat {
let redColor = redCol + redInc
cell.textLabel?.textColor = UIColor.white()
cell.textLabel?.backgroundColor = UIColor.clear()
cell.contentView.backgroundColor = UIColor.clear()
cell.backgroundColor = UIColor(
red: redColor, green: 0.3, blue: 0.95, alpha: 1.0)
let selectedView = UIView()
selectedView.backgroundColor = SELECTEDCOLOR
cell.selectedBackgroundView = selectedView
return redColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class Contact: NSObject {
//MARK: プロパティ
var z氏名:String
var zよみ:String
var z性別:String
var z生年月日:String
var z電子メール:String
var z写真:UIImage?
//MARK: イニシャライザ
init(_ 氏名:String, _ よみ:String, _ 性別:String,
_ 生年月日:String, _ 電子メール:String,
写真:UIImage?=nil) {
self.z氏名 = 氏名
self.zよみ = よみ
self.z性別 = 性別
self.z生年月日 = 生年月日
self.z電子メール = 電子メール
self.z写真 = 写真
}
}
import Foundation
class ContactRepo {
var contacts: [Contact]
init() {
// TODO: 今はハードコーディング
contacts = []
contacts.append(Contact("相田翔子", "あいだしょうこ", "F", "1977/03/03", "[email protected]"))
contacts.append(Contact("秋山真太郎", "あきやましんたろう", "M", "1975/04/03", "[email protected]"))
contacts.append(Contact("倉田健一", "くらたけんいち", "M", "1987/12/23", "[email protected]"))
contacts.append(Contact("佐々木陽子", "ささきようこ", "F", "1972/01/08", "[email protected]"))
...
contacts.append(Contact("寺田聖子", "てらだせいこ", "F", "1967/03/13", "[email protected]"))
}
func findAll() -> [Contact] {
return contacts.sorted(isOrderedBefore: {c1, c2 in c1.zよみ < c2.zよみ})
}
func findByEmail(_ email:String) -> Contact? {
var contact:Contact? = nil
for c in contacts {
if c.z電子メール == email {
contact = c
}
}
return contact
}
}
import UIKit
/*:
サンプル01のためのテーブルビュー・コントローラ.
テーブルビュー:(コンテント:動的プロトタイプ, スタイル :プレーン)
データソース: contacts
セルID:TableView01Cell
*/
class TableViewController01: UITableViewController {
let contactRepo = ContactRepo()
var contacts: [Contact] = []
let SELECTEDCOLOR = UIColor(red: 0.4, green: 0.90, blue: 0.95, alpha: 1.0)
let CELLBGCOLOR = UIColor(red: 0.5, green: 0.95, blue: 1.0, alpha: 1.0)
let ROW_HEIGHT:CGFloat = 62
override func viewDidLoad() {
super.viewDidLoad()
// 連絡先リポジトリから連絡先全件を取得.
contacts = contactRepo.findAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - データソース
override func numberOfSections(in tableView: UITableView) -> Int {
// セクション数を返す.
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// テーブルの行数を返す.
return contacts.count
}
// セルオブジェクトをTable Viewに提供(UITableViewDatasource の必須メソッド)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableView01Cell", for: indexPath)
// セルの設定
let contact = contacts[(indexPath as NSIndexPath).row]
cell.textLabel!.text = contact.z氏名
cell.detailTextLabel!.text = contact.z生年月日
if contact.z性別 == "F" {
cell.imageView?.image = UIImage(named: "female")
} else {
cell.imageView?.image = UIImage(named: "male1")
}
setLabelAttr((cell.textLabel)!, fontSize: 28)
setLabelAttr((cell.detailTextLabel)!, fontSize: 18)
cell.backgroundColor = CELLBGCOLOR
let selectedView = UIView()
selectedView.backgroundColor = SELECTEDCOLOR
cell.selectedBackgroundView = selectedView
return cell
}
// ラベルのプロパティ(文字の色, 背景の色, フォント)を設定
func setLabelAttr(_ lbl: UILabel, fontSize: CGFloat) {
lbl.textColor = UIColor.darkGray()
lbl.backgroundColor = UIColor.clear()
lbl.font = UIFont(name: "Avenir Next", size: fontSize)
}
override func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return ROW_HEIGHT
}
}
import UIKit
/*:
サンプル02のためのテーブルビュー・コントローラ.
テーブルビュー:(コンテント:動的プロトタイプ, スタイル :プレーン,
セクション数:連絡先のよみでセクションに分割する)
データソース: contacts
セルID:TableView02Cell
*/
class TableViewController02: UITableViewController {
let contactRepo = ContactRepo()
var contacts: [Contact] = []
let secTitles = ["あ","か","さ","た","な","は","ま","や","ら","わ","ん"]
var sections : [(index: Int, length :Int, title: String)] = Array()
override func viewDidLoad() {
super.viewDidLoad()
contacts = contactRepo.findAll()
setupSections(contacts)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 連絡先の全件をよみで以下の条件でセクションに分割する.
// 条件=セクションタイトル(n) <= よみ < セクションタイトル(n+1)
// 各セクションの情報はタプル(index: Int, length :Int, title: String)に保持する
func setupSections(_ contacts: [Contact]) {
var secIdx = 0
var secTitle = secTitles[secIdx]
var nextSecTitle = secTitles[secIdx+1]
var dataIdx = 0
var curTitle = secTitle
for i in 0 ..< contacts.count {
if secTitle <= contacts[i].zよみ &&
contacts[i].zよみ < nextSecTitle {
curTitle = secTitle
} else {
if secTitle == curTitle {
sections.append((index: dataIdx,
length: i - dataIdx,
title: secTitle))
dataIdx = i
} else {
sections.append((index: dataIdx,
length: 0,
title: secTitle))
}
secIdx += 1
secTitle = secTitles[secIdx]
nextSecTitle = secTitles[secIdx+1]
}
}
}
// MARK: - データソース
/// セクション数を返す.
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
/// セクションごとの行数を返す.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].length
}
/// 行ごとのテーブルのセルを設定して返す
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "TableView02Cell", for: indexPath)
// セルの設定
let index = sections[(indexPath as NSIndexPath).section].index + (indexPath as NSIndexPath).row
cell.textLabel?.text = contacts[index].z氏名
cell.detailTextLabel?.text = contacts[index].zよみ
return cell
}
/// セクションのタイトルを返す
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String {
return sections[section].title
}
override func sectionIndexTitles(
for tableView: UITableView) -> [String]? {
return sections.map { $0.title }
}
//
override func tableView(_ tableView: UITableView,
sectionForSectionIndexTitle title: String,
at index: Int) -> Int {
return index
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment