目的:
CustomでtableViewCellをStoryboardと協調して作成する際の自分なりの方法を説明する
環境:
Xcode Version 6.1.1
実装方針:
Debugのしやすさや見た目でのバランスを確認しながら実装したいので、私はStoryboardを使用しています。tableViewCellを配置してそこに以下のもののをのっけってTagナンバー付けています。
Tag Number | UI | 目的 |
---|---|---|
1 | imageView | itemのimage表示 |
2 | textLabel | itemの名前表示 |
3 | textView | itemの詳細説明用 |
tableViewのDelegate内では以下のようにcellを渡すとします。
func tableView(
tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
let shop = self.shops[indexPath.row]
ShopTableViewCell(cell: cell, cellDataSource: shop)
return cell
}
事前にcellに表示したい情報等をshops配列に準備しています。それをcellDataSourceとして
自作したShopTableViewCellに渡しています。そのあとはShopTableViewCellないで表示等の処理をしています。
ソースコードと詳細説明
具体的にShopTableViewCellの中身を示します。
import UIKit
class ShopTableViewCell: UITableViewCell {
// --- Properties ---
// MARK: Properties
private var cell:UITableViewCell!
private var shop:Shop!
// --- Initializer ---
// MARK: Initializer
override init() {
super.init()
}
init(cell name:UITableViewCell, cellDataSource:Shop){
super.init()
self.cell = name
self.shop = cellDataSource
self.setupTableCell()
}
// required initializer
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
// --- methods ---
// MARK: methods
private func setupTableCell(){
var image = self.cell.viewWithTag(1) as UIImageView
var shopname = self.cell.viewWithTag(2) as UILabel
var comment = self.cell.viewWithTag(3) as UITextView
// --- setup shopname
shopname.text = self.shop.name
// --- setup cell imageView
var q_global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
var q_main = dispatch_get_main_queue()
dispatch_async(q_global, { () -> Void in
let url = self.shop.imageURLs[0]
let data = NSData(contentsOfURL: NSURL(string: url)!)
let imageData = UIImage(data: data!)
dispatch_async(q_main, { () -> Void in
image.contentMode = UIViewContentMode.ScaleAspectFit
image.image = imageData!
})
})
}
}
swiftから導入されたinitで、propertyの初期化だけでなくcellのsetupまでを実施しています。cellのsetupは別途setupTableCell()を定義しています。setupTableCell()内では事前につけていたtagを識別子として変数を作っています。
self.cell.viewWithTag(1) as UIImageView
のあたりです。
あと今回使用した特徴はinit内でMethodを呼ぶようにしたポイントです。objectが生成された時点ですべてのsetupが終了します。