我的tableView显示卡片列表
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = cardsTable.dequeueReusableCellWithIdentifier("SelectableCardCell", forIndexPath: indexPath) as! CardSelectionTableViewCell
let cardCell: Card!
if self.delegate is CardsApprovalsViewController {
cardCell = approvalCards[indexPath.row] // approvalCard array of type card
} else {
cardCell = fetchedResultsController.objectAtIndexPath(indexPath) as! Card
}
cell.policyHolderName.text = cardCell.policy_holder_name
cell.alphaMark.text = cardCell.policy_holder_name.substringToIndex(advance(cardCell.policy_holder_name.startIndex, 1)).uppercaseString
var image: NSData = cardCell.photo as NSData
cell.picture.highlightedImage = UIImage(data: image)
cell.cardNumber.text = cardCell.member_id
cell.policyNumberLabel.text = cardCell.policy_no
cell.insuranceNameLabel.text = cardCell.insurance.company_name
return cell
}
Afetr选择一个单元格,我希望隐藏cell.alphaMark标签以显示cell.picture.highlightedImage
如果用户选择另一个单元格,则上一个单元格的cell.alphaMark应该再次出现
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var selectedCell: CardSelectionTableViewCell = cardsTable.cellForRowAtIndexPath(indexPath) as! CardSelectionTableViewCell
selectedCell.alphaMark.hidden = true
let newSwiftColor = UIColor(red: 224, green: 227, blue: 224)
selectedCell.contentView.backgroundColor = newSwiftColor
if self.delegate is CardsApprovalsViewController {
self.card = approvalCards[indexPath.row]
} else {
self.card = fetchedResultsController.objectAtIndexPath(indexPath) as! Card
}
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
var selectedCell = cardsTable.cellForRowAtIndexPath(indexPath) as! CardSelectionTableViewCell // Some times crashes here
selectedCell.alphaMark.hidden = false
}
当我选择单元格并选择另一个单元格...等(重复选择单元格)时,alphaMark和picture.highlightedImage工作正常,但随后它停止并让我在解开一个可选值时意外地发现了nil#34 ;错误
我检查了单元格的出口,并将它们连接到故事板
有人可以帮我解决这个错误吗? 感谢
答案 0 :(得分:3)
防止崩溃的最简单方法是更改强制解包可选内容并使用if let
代替:
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let selectedCell = cardsTable.cellForRowAtIndexPath(indexPath) as? CardSelectionTableViewCell {
selectedCell.alphaMark.hidden = false
}
}
这会考虑到cardsTable.cellForRowAtIndexPath(indexPath)
可能会返回nil,因此尝试将其解包为CardSelectionTableViewCell
不会失败(因为您无法将nil解包为CardSelectionTableViewCell
)< / p>
这可以防止崩溃,但它不会完全完成你想要做的事情。您还需要更新cellForRowAtIndexPath
以检查当前单元格是否为selected
并正确更新alphaMark.hidden
。
因此,如何做到这一点的一个快速解决方法是将其添加到cellForRowAtIndexPath
的末尾,以便每次将单元格置于屏幕上时,基于单元格有条件地隐藏alphaMark
被选中:
cell.alphaMark.hidden = cell.selected