2014-12-30 38 views
1

我在故事板創建自定義的UITableView單元格,看起來像這樣:疑難解答自定義的UITableView細胞[斯威夫特]

enter image description here

我迷上它給我的UITableViewCell類,像這樣:

進口UIKit的

class StatusCell: UITableViewCell { 

@IBOutlet weak var InstrumentImage: UIImageView! 

@IBOutlet weak var InstrumentType: UILabel! 

@IBOutlet weak var InstrumentValue: UILabel! 

override func awakeFromNib() { 
    super.awakeFromNib() 
} 

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

最後,我試圖從我的UIViewController這樣初始化的UITableView:

import UIKit 

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

@IBOutlet weak var TableView: UITableView! 

let Items = ["Altitude","Distance","Groundspeed"] 

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

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

    var cell: StatusCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as StatusCell! 

    cell.InstrumentType?.text = Items[indexPath.row] 
    cell.InstrumentValue?.text = "150 Km" 
    cell.InstrumentImage?.image = UIImage(named: Items[indexPath.row]) 
    return cell 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

} 

然而,當我嘗試運行該程序,我得到一個錯誤EXC_BAD_INSTRUCTION:

enter image description here

什麼可能我做錯了?任何幫助,將不勝感激!

+0

你加'cellIdentifier'在您的單元的界面生成器中? – Sauvage

+0

對於我在Identity Inspector中的自定義單元格,「恢復ID」設置爲「單元格」。 – user3185748

+0

您需要設置'重用標識符',而不是'恢復ID'。 – Sauvage

回答

0

調試器輸出顯示cellnil,這意味着它不能被實例化。此外,您正在強制展開可選(使用!),導致應用程序在nil值上崩潰。

試圖改變自己的cellForRowAtIndexPath方法,像這樣(注意dequeueReusableCellWithIdentifier法):

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as StatusCell 

    cell.InstrumentType.text = Items[indexPath.row] 
    cell.InstrumentValue.text = "150 Km" 
    cell.InstrumentImage.image = UIImage(named: Items[indexPath.row]) 

    return cell 
} 

假設您的自定義tableViewCell類是正確設置和出口的限制,也沒有必要檢查自選。

let cell = ...行上放置一個斷點並逐步完成代碼。檢查cell是否被初始化,而不是nil

並請:不要使用屬性和變量大寫的名字(你的網點,Items陣列...)爲大寫的名字是類,結構,...

+0

謝謝你的輸入,我剛剛修復了大寫變量。至於代碼,我插入了一些斷點,發現'let cell'行以及後兩行。當我在'cell.InstrumentValue.text'的斷點處按下繼續時,我得到了這個錯誤,並感到困惑:https://imgur.com/RUIqkay – user3185748

+0

仔細檢查你的網點是否在InterfaceBuilder中正確綁定。可以肯定的是,刪除並重新創建它們。 – zisoft

+0

非常感謝!事實證明,我原來錯誤地限制了我的網點。祝你有美好的一天! – user3185748