UITableView にカスタム セルをロードする必要があります。「CustomTableViewCell」という名前の UITableViewCell のカスタム サブクラスを作成しました。図に示すように、(ドラッグ アンド ドロップを使用して) テーブルビューに UITabelViewCell を追加しました。次に、ファイル インスペクタで、その UITabelViewCell のクラスを「CustomTableViewCell」に設定しました。これが私のコードです:
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView : UITableView
var items = String[]()
override func viewDidLoad() {
super.viewDidLoad()
items = ["Hi","Hello","How"]
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "CusTomCell")
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
return items.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
var cell:CustomTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("CusTomCell") as? CustomTableViewCell
if !cell
{
cell = CustomTableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "CusTomCell")
}
println("cell \(cell)")
// cell.?.labelTitle.text = items[indexPath.row]
cell!.labelTitle.text = "some text"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
コードを実行すると、「致命的なエラー: Optional.None をアンラップできません」というエラーが表示されます (画像を参照)。