【发布时间】:2017-06-08 07:34:31
【问题描述】:
祝大家有美好的一天。遇到了问题。我需要用一个按钮制作一个表格,然后通过单击该按钮,我会收到一个带有单元格编号的警报。表格单元格本身是不活动的。我就是这样意识到的。当我一开始滚动表格时一切都很好,当你按下按钮时,会显示一个带有正确行号的警报,但在 4 个元素之后出现错误。
此错误出现在我使用 4 标记的行中。 致命错误:在展开可选值时意外发现 nil
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell
if (tableView.tag == 1) {
let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel
numLabel.text = String(indexPath.row)
} else if (tableView.tag == 2) {
//Error appears here
let numButton: UIButton = tableView.viewWithTag(4) as! UIButton
numButton.setTitle(String(indexPath.row), for: .normal)
numButton.tag = indexPath.row
}
return cell
}
@IBAction func showAlertForRow(row: UIButton) {
let alert = UIAlertController(title:"Test work",message:"Cell at row \(row.tag) was tapped!",preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
【问题讨论】:
-
这是因为带有标签 4 的 UIButton 一旦离开屏幕就不再可用。这种方法感觉不对,为此创建一个自定义单元格。
-
这是什么
tableView.viewWithTag(3)你在tableview里面添加子视图的地方?,如果我没记错应该有单元格 -
我在一个视图控制器中有两个表。第一个表中有标签。我为我的元素提供了标签号。第一个表 - 1,第二个表 - 2,第一个表的标签 - 3 和第二个表的按钮 - 4。也许我应该这样做 - 可选绑定?但是我不明白在其他情况下该怎么写?
-
if (tableView.tag == 1) { let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel numLabel.text = String(indexPath.row) } else if (tableView.tag == 2) { if let numButton: UIButton = tableView.viewWithTag(4) as? UIButton { numButton.setTitle(String(indexPath.row), for: .normal) numButton.tag = indexPath.row } else { } } -
@Crowl:如果答案有帮助,希望您能接受。 :)
标签: ios swift uitableview uialertcontroller tableviewcell