在uitableviewcontroller中解包一个Optional值时意外地发现了nil

时间:2015-03-08 10:30:47

标签: ios uitableview swift

当我实际运行代码时出现此错误(此行是问题 var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId)as UITableViewCell 。这是在UITableViewController类中。

import UIKit

class AlarmsTableViewController: UITableViewController {

var myData:Array<AnyObject> = []



override func viewDidLoad() {
    myData = ["one", "two", "three", "four"]
}

override func didReceiveMemoryWarning() {

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myData.count
}

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

    let CellId:String = "Cell"
    var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId) as UITableViewCell

    //if let ip = indexPath {
        cell.textLabel?.text = myData[indexPath.row] as? String
    //}


    return cell
}


override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {

    return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        //Delete row from data source
        //if let tv = tableView? {
            myData.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)


    } else if editingStyle == .Insert {

    }
}


}

1 个答案:

答案 0 :(得分:0)

在界面构建器中,选择与您一起使用的TableViewController。然后,选择原型单元格并将其样式设置为“Basic”。最后,将单元格重用标识符设置为Cell。