我在设备上测试代码时收到错误:fatal error: unexpectedly found nil while unwrapping an Optional value
。
我正在为TableViewController实现一些代码,以便在触摸/按下时突出显示某些TableView单元格。
我已将问题隔离到'row 6',这是我的TableView的最后一行。当我注释掉这一行的代码时,代码运行得很完美。
我已经以编程方式(以及在StoryBoard中)将行数设置为7。
我只是不明白错误发生的原因。显然它无法打开最后一个细胞,但我不明白为什么。
这是我的代码:
注意:第0行和第1行(前两行)不是“可点击的”,因此我的代码中没有引用它们。
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 7
}
//Make TableView Cells Highlight On Touch Respectively.
override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))
cell!.contentView.backgroundColor = UIColor(red: 170/255, green: 139/255, blue: 255/255, alpha: 1.0)
let cell1 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))
cell1!.contentView.backgroundColor = UIColor(red: 138/255, green: 231/255, blue: 36/255, alpha: 1.0)
let cell3 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0))
cell3!.contentView.backgroundColor = UIColor(red: 135/255, green: 190/255, blue: 255/255, alpha: 1.0)
let cell4 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 5, inSection: 0))
cell4!.contentView.backgroundColor = UIColor(red: 250/255, green: 236/255, blue: 67/255, alpha: 1.0)
let cell5 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 6, inSection: 0))
cell5!.contentView.backgroundColor = UIColor(red: 182/255, green: 181/255, blue: 182/255, alpha: 1.0)
}
override func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))
cell!.contentView.backgroundColor = .clearColor()
let cell1 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))
cell1!.contentView.backgroundColor = .clearColor()
let cell3 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0))
cell3!.contentView.backgroundColor = .clearColor()
let cell4 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 5, inSection: 0))
cell4!.contentView.backgroundColor = .clearColor()
let cell5 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 6, inSection: 0))
cell5!.contentView.backgroundColor = .clearColor()
}
感谢您提前的时间: - )
答案 0 :(得分:2)
根据Apple docs for cellForRowAtIndexPath
返回值 表示表格单元格的对象,如果单元格不可见或indexPath超出范围,则为nil。
您在方法中创建实例变量以引用单元格并强制在下一行中展开它们。您尝试强制解包的最后一个单元格可能不可见,并且该方法返回nil,因为该单元格不存在/该行的单元格尚未出列。
如果您真的希望所有单元格都改变颜色,您可能希望使用if let语句来防止nil单元格,如果您只打算更改一个单元格的颜色,则可能需要使用switch语句。
答案 1 :(得分:1)
避免以几乎所有费用强制展开!
if let cell5 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 6, inSection: 0)){
cell5.contentView.backgroundColor = UIColor(red: 182/255, green: 181/255, blue: 182/255, alpha: 1.0)
}