自定义UITableviewcell在swift中显示“致命错误:不能解包Optional.None”问题

我需要加载一个UITableView的自定义单元格。 我创build了名为“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”在图像中看到。

嗨最后,我find了我的问题的解决scheme..请检查我的代码..它适用于我..

 class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet var tableView : UITableView var items = String[]() override func viewDidLoad() { super.viewDidLoad() items = ["Hi","Hello","How"] // 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", forIndexPath: indexPath) as? CustomTableViewCell cell!.labelTitle.text = "some text" return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

第1步:在下面的viewDidLoad()中注册nib

 var xib : UINib = UINib (nibName: "WeatherTableViewCell", bundle: nil) self.tableView.registerNib(xib, forCellReuseIdentifier: "Cell") 

第2步:在cellForRowIndexPath中添加以下内容

 var cell:WeatherTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("Cell") as? WeatherTableViewCell cell!.weatherName.text = "weather" return cell 

self.tableView.dequeueReusableCellWithIdentifier将只返回一个单元格,如果有一个更早创build。 你必须做一个零检查,并创build一个新的单元格,如果它是零。 在你的情况下,它会出现错误的cell.labelTitle.text =因为单元格可能在那里。