iOS - UITableViewCell,UIAlertController

时间:2017-06-08 07:34:32

标签: ios swift uitableview uialertcontroller tableviewcell

大家好日子。面临一个问题。我需要用一个按钮创建一个表,然后单击按钮,我会得到一个包含单元格编号的警报。表格单元格本身不活动。这就是我意识到的。当我在开始时滚动表格时一切都很好,当你按下按钮时,会显示一个带有正确行号的警报,但是在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)
}

1 个答案:

答案 0 :(得分:2)

您为实施此程序而设计的内容不正确。你能做什么

  1. 制作自定义单元格
  2. 在自定义单元格中添加按钮
  3. 在CellForRowAtIndexPath
  4. 中的该按钮中添加操作
  5. 处理ViewController中添加tableView的操作。
  6. 我为你做了一个完整的项目。只是让你知道。如果你想在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)
    
    
    }
    

    只检查三个文件:

    Github link

    1. ViewController.swift

    2. sampleTableViewCell.swift

    3. sampleTableViewCell.xib **

    4. 这是输出:

      enter image description here