HOME > UITableViewCellをプログラムで動的に作成する
UITableViewCellをプログラムで動的に作成する
UITableViewをStoryboardで作成する方法は結構ありますが、プログラムだけで作成するサンプルが少なかったので共有します。
UITableViewCellのクラス階層
NSObject
↑
UIResponder
↑
UIView
↑
UITableViewCell
参考:UIKit Framework Reference UITableViewCell Class Reference
参考:custom UITableCellView programmatically using swift
参考:Creating a UITableViewCell programmatically in Swift
やってみた
init処理を二つ(overrideとrequired)追加する必要があるのでハマりました。
まずUITableViewCellの独自クラスを作成します。
import UIKit
class CustomTableViewCell: UITableViewCell
{
var titleLabel = UILabel();
var contentLabel = UILabel();
override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
//First Call Super
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = UILabel(frame: CGRectMake(10, 2, 300, 15));
titleLabel.text = "";
titleLabel.font = UIFont.systemFontOfSize(12)
self.addSubview(titleLabel);
contentLabel = UILabel(frame: CGRectMake(10, 20, 300, 15));
contentLabel.text = "";
contentLabel.font = UIFont.systemFontOfSize(22)
self.addSubview(contentLabel);
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
}
こんな感じです。その次にTableViewのDelegate部分と宣言部分の2箇所を微調整。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as CustomTableViewCell
cell.titleLabel.text = self.items[indexPath.row]
cell.contentLabel.text = "ホゲホゲ";
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
DelegateのcellForRowAtIndexPathと...
//tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
UITableView宣言時のregisterClass...
これで動的に作成したカスタムクラスをStoryboard無しで追加できます。
カスタマイズ
特になし
まとめ
一度作ってしまえば簡単なのですが、、、、結構ハマってしまいましのたでソースが助けになれば嬉しいです。UITableViewの記事はこちらからどうぞ!
↓こんな記事もありますよ!
![]() | CoreTextをイラストで理解してみる上記がAppleのCoreText説明に記載されているイラスト図ですが正直よくわかりません。文章を三角や丸等の領域に表示したり、一行だけ表示したり、一文字だけ表示したり、 と様々な使い方ができるようです。 |
![]() | カスタムクラスを作成時いつも忘れる。継承クラス作成時のメモカスタムクラスを作成する時いつもUIViewを継承する際のrequired Initの箇所でハマってしまうので覚書です。 |
![]() | UIWebViewアプリの中にWebビューを作成して外部ネットワークやローカルのhtmlやcssやjsファイルと連携する方法の説明です。 |
Tweet
![]() |
|||
|