大家好。遇到了问题。我需要制作一个带有按钮的表格,然后单击该按钮,我会收到有关单元格编号的警报。表格单元格本身不活动。我就是这样意识到的。当我一开始滚动表格时一切正常,当您按下按钮时,会显示带有正确行号的警报,但在 4 个元素后出现错误。
此错误出现在我使用 4 标记的行中。 fatal error :在展开可选值时意外发现 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)
}
最佳答案
您为实现此过程而设计的内容不正确。你能做什么
- 制作自定义单元格
- 在自定义单元格中添加按钮
- 在 CellForRowAtIndexPath 中的该按钮中添加操作
- 处理来自添加了 tableView 的 ViewController 的操作。
我为你做了一个完整的项目。只是想让你知道。如果你想在 tableView 中添加 customCell,你需要像这样在 viewDidLoad 中注册它。 我所做的是在 ViewController.swift 文件中。查看我的项目。
let nib = UINib.init(nibName:String(describing: sampleTableViewCell.self) , bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "chatCell")
然后检查 cellForRowAtIndexPath 函数:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell
cell.clickMeBtn.tag = indexPath.row
cell.clickMeBtn.addTarget(self, action: #selector(onButtonPressed(sender :)), for: .touchUpInside)
return cell
}
按键功能:
func onButtonPressed(sender:UIButton) {
let alert = UIAlertController.init(title:"Cell index is"+String(sender.tag), message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction.init(title: "ok", style: UIAlertActionStyle.default) { (UIAlertAction) in
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
只检查三个文件:
ViewController.swift
sampleTableViewCell.swift
sampleTableViewCell.xib**
这是输出:
关于iOS - UITableViewCell, UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429411/