2014-07-18 20 views
12

很簡單代碼:簡單的UITableView - 意外發現零

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

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int { 
    return 5 
} 


func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! { 
    let cell: BookTableViewCell = BookTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "BookCell") 
    println("ip: \(indexPath.row)") 
    cell.bookLabel.text = "test" 

    return cell 
} 

在cell.bookLabel.text線我得到這個:

fatal error: unexpectedly found nil while unwrapping an Optional value 

的BookTableViewCell的定義是這樣的:

class BookTableViewCell: UITableViewCell { 

    @IBOutlet var bookLabel: UILabel 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
    } 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 
    } 

} 

而bookLabel正確地連接在Storyboard中的Prototype單元格中。爲什麼我得到這個錯誤?

回答

7

當您在代碼中創建視圖時,其IBOutlet屬性未正確連接。你希望你從dequeueReusableCellWithIdentifier找回版本:

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell 
+12

仍然不適合我。 – JohnVanDijk

57

如果你使用的故事板,請確保你沒有這條線在你的文件的開頭:

self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell") 

它將覆蓋故事板,因此,故事板中的出口鏈接將被忽略。

+6

對我來說,這是正確的答案......把我的頭髮拉出來。 –

+3

謝謝!這是答案 – Led

+0

非常感謝。當我以編程方式完成所有事情時,我習慣於寫這篇文章。 – Cesare

15

我得到了這個錯誤,因爲我沒有在自定義單元格的故事板中寫入標識符。

StoryBoard

另外,還要確保它,你的代碼匹配:

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

     let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell 

     ... 
    } 
6

可能您在Main.Storyboard視圖失去的ViewController文件的IBOutlet中引用,只需再次將其鏈接。

+0

這很簡單,但最後它對我有用。 –

+0

在我的情況下,我有一個陳舊的IBOutlet引用導致這個錯誤。感謝您的建議。 –

1

在我的情況是這樣的可選被解開:

let cellId:String = "ConverterTableCell" 
let cell: ConverterTableViewCell = (tableView.dequeueReusableCellWithIdentifier(cellId)! as? ConverterTableViewCell)! 
0

試着這樣做:

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell", forIndexPath: indexPath) as! BookTableViewCell 

,不要忘記設置重複利用標識在故事板

0

每當我使用重用Identifer名稱不同於自定義類名稱 unifid這些名字爲我解決它

1

不要忘記註冊筆尖(用Swift3測試),例如, G。裏面覆蓋FUNC viewDidLoad中()

self.tableView.register(UINib(nibName: "BookTableViewCell", bundle: nil), forCellReuseIdentifier: "BookCell") 
0

我遇到這個錯誤,如果我把UITapGestureRecognizer中的故事情節進行自定義的UITableViewCell(Xcode的版本爲8.3)。

相關問題