意外地发现零,而迅速展开一个可选的值

我从下面的类中得到了一个错误信息“意外地发现了nil而从Swift解开一个Optional ”。 错误发生在线上:

 (cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String 

我有一个自定义单元类与2 UILabels标记1和2,网点设置

  import UIKit import Foundation class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ var objects = NSMutableArray() var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]] @IBOutlet var tableView: UITableView! var items: [String] = ["We", "Heart", "Swift"] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count;//self.items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell //cell.textLabel?.text = self.items[indexPath.row] //return cell let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell let object = dataArray[indexPath.row] as NSDictionary (cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String (cell.contentView.viewWithTag(2) as UILabel).text = object["lastName"] as? String return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("You selected cell #\(indexPath.row)!") } } 

如果你想使用自定义单元布局,我会build议

  1. 子类UITableViewCell

     // CustomTableViewCell.swift import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var firstNameLabel: UILabel! @IBOutlet weak var lastNameLabel: UILabel! } 
  2. 在故事板中创build表格视图。 添加细胞原型到故事板中的tableview。 devise细胞原型(添加任何你想要的标签)。

  3. 指定单元格原型的故事板标识符是任何你想要的(在你的例子MyCell )。

    在这里输入图像说明

  4. 指定单元格原型的基类(在本例中为CustomTableViewCell

    在这里输入图像说明

  5. 连接你的单元格原型和你的UITableViewCell子类之间的IBOutlet引用。

    在这里输入图像说明

    注意IBOutlet引用左侧的实心项目符号。 这表明出口连接正确。

  6. 在数据源中实现cellForRowAtIndexPath ,例如在Swift 3中:

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! CustomTableViewCell let person = dataArray[indexPath.row] cell.firstNameLabel.text = person["firstName"] cell.lastNameLabel.text = person["lastName"] return cell } 

    或者在Swift 2中:

     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! CustomTableViewCell let person = dataArray[indexPath.row] cell.firstNameLabel.text = person["firstName"] cell.lastNameLabel.text = person["lastName"] return cell } 
  7. 请注意,如果使用单元格原型,则不需要viewDidLoad调用registerClass 。 故事板将自动注册您的自定义类与您重用的标识符(因为你已经在步骤3和4做了什么)。

编辑2:这个解决scheme可能更适合你的目的。 有了这个,你可以为你自己的UITableViewCell创build自己的类,并使用它重用模式。 注释在代码中:

  class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ // The data var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]] // The outlet to your tableview in the ViewController in storyboard @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Create a nib for reusing let nib = UINib(nibName: "MyCell", bundle: nil) // Register the nib for reusing within the tableview with your reuseidentifier tableView.registerNib(nib, forCellReuseIdentifier: "MyCell") // Set delegate and datasource to self (you can do that in interface builder as well tableView.delegate = self tableView.dataSource = self } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count; // return the number of datasets } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // create a reusable cell with the reuse identifier you registered in viewDidLoad and cast it to MyCell let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell let object = dataArray[indexPath.row] as NSDictionary // set the strings matching your array cell.label1.text = object["firstName"] as? String cell.label2.text = object["lastName"] as? String // return the cell return cell } // some example for the delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("You selected cell #\(indexPath.row)!") } } // class for you own UITableViewCell // has own xib file class MyCell: UITableViewCell { // two outlets representing two labels in the xib file @IBOutlet private weak var label1: UILabel! @IBOutlet private weak var label2: UILabel! } 

为了这个工作,你必须创build一个名称正确的xib文件(本例中为MyCell)。 它应该类似于这样的:

在这里输入图像说明

设置自定义视图的类和出口是非常重要的。

————————————-其他解决scheme———– —————————

编辑:正如我所看到的,你不初始化你自己的类“MyCell”,但苹果的类'UITableViewCell'与reuseIdentifier'MyCell'。 所以这是使用UITableViewCell的解决scheme:

该行(cell.contentView.viewWithTag(1) as UILabel)不仅是一个(cell.contentView.viewWithTag(1) as UILabel)到特定的类,它也展开了可选的(UIView)。 你在其他情况下用“!”来做。 所以问题是:你正在创build一个Apple创build的类UITableViewCell的实例。 你想用特定的标签获取该视图的子视图。 你怎么知道苹果给他们这些标签? 你真正想要的是创build一个具有特殊风格的UITableViewCell的实例,并设置textLabels的值如下所示:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Create an instance of UITableViewCell. Style is .Subtitle but could be others as well var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as? UITableViewCell let object = dataArray[indexPath.row] as NSDictionary // set the strings matching your array cell?.textLabel?.text = object["firstName"] as? String cell?.detailTextLabel?.text = object["lastName"] as? String // return the cell return cell! } 

我所要做的只是:

 cell.subviews[0].subviews[0].viewWithTag(//your tag//)