我需要在 UITableView 中加载自定义单元格。我创建了一个名为“CustomTableViewCell”的自定义 UITableViewCell 子类。如图所示,我已将 UITabelViewCell 添加到 tableview(使用拖放)。然后在文件检查器中,我将该 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”,如图所示。