在更新单元格中的标签时,在展开Optional值时意外发现nil

时间:2016-03-01 15:27:28

标签: ios swift uitableview fatal-error

我的代码如下,但我收到的错误与注释掉的行的标题相同。我尝试过可选绑定但仍然无法正常工作。我已经在viewDidLoad中更新了日期数组,所以不确定为什么它找到了nil,任何想法?谢谢!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = myTableView.dequeueReusableCellWithIdentifier("logCell", forIndexPath: indexPath) as! logViewCell

   let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MMM-yy"
    // cell.date.text = dateFormatter.stringFromDate(dates[indexPath.row])       
}

我的自定义单元格的代码:

class LogViewCell: UITableViewCell {

@IBOutlet var date: UILabel!

}

1 个答案:

答案 0 :(得分:0)

在viewDidLoad中注册您的课程为

self.myTableView.registerClass(LogViewCell.self, forCellReuseIdentifier:"logCell") ViewController.dateFormatter.dateFormat = "dd-MMM-yy"

在视图控制器中声明一个静态属性

static var dateFormatter = NSDateFormatter()

然后将您的功能更改为:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{
    if let cell = myTableView.dequeueReusableCellWithIdentifier("logCell", forIndexPath: indexPath) as? LogViewCell {
            cell.date.text = ViewController.dateFormatter.stringFromDate(dates[indexPath.row])       
        } else {
          print("Could not get the required cell") 
          return nil
        }
    }