2014-12-30 39 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