我在 Storyboard中创建了一个自定义的 UITableView 单元格,如下所示:
我像这样将它连接到我的 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 错误:
我可能做错了什么?任何帮助将不胜感激!
最佳答案
调试器输出显示 cell
为 nil
,这意味着它无法实例化。此外,您强制解包可选(使用 !
),这会导致应用程序在 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 类已正确设置并且导出已绑定(bind),则无需检查可选值。
在 let cell = ...
行上放置一个断点并单步执行代码。检查 cell
是否已初始化并且不是 nil
。
请:不要将大写名称用于属性和变量(您的导出、Items
数组...)作为大写名称用于类、结构、...
关于ios - 自定义 UITableView 单元格故障排除 [Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709820/