UITabelViewCellを使ってカスタムセルのテーブルを作りたかったので,紹介しておきます.
セルについては.xibファイルを用意するものとします.
ただし,配置するパーツなどはすべてswif側で用意してしまうので,まさに空っぽのビューだけ作っておけば大丈夫です.
まず,Cell側,
xibファイルの該当するセルと関連付けておいてください.
testCustomViewCell.swift
import UIKit class testCustomViewCell: UITableViewCell { required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) // UILabelとかを追加 } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
次にtable側.
testCustomTableViewController.swift
import UIKit class testCustomTableViewController: UITableViewController { override func viewDidLoad() { // ここで登録しておかないと,cellを作るときに見つけられない self.tableView.registerClass(testCustomViewCell.classForCoder(), forCellReuseIdentifier: "testCustomViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. // テーブルのrowの数 return 10 } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { // viewDidLoadで登録したIdentifireから見つける var cell = tableView.dequeueReusableCellWithIdentifier("testCustomViewCell", forIndexPath: indexPath) as testCustomViewCell // cellの中身は好きにカスタマイズ return cell }
これで,testCustomViewCellで書いたとおりのセルでテーブルを実現できます.
デフォルトで用意されているテーブルのセルデザインって,イメージと,タイトル,サブタイトルくらいなもので,結構少ないですよね.
自分でそれなりの情報を表示しようと思ったら足らないし,使えると楽です.
全然関係ないのですが,はてながswiftのシンタックスハイライトに対応していない気がして……なんかいい感じにコードを見やすくしておきたいですね…….