在TableView
中有一个ViewController
,TableViewCell
有一个包含一些内容的textView。现在,在单击replyButton
后,在一个cell
中,segue
到secondViewController
。我需要将内容放在textView
of cell
中。该怎么做呢?下面我使用indexPath
作为代码,但是它崩溃了,因为indexPath
是nil
。谢谢你的帮助。
说明:我需要单击单元格内的replyButton来实现目标,而不是使用didSelectRowAtIndexPath函数。
代码:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBAction func replyButtonTapped(_ sender: Any) {
self.performSegue(withIdentifier: "toReplyVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toReplyVC" {
let replyVC = segue.destination as! ReplyVC
// code below did't work:
/*
let indexPath = self.repliesTableView.indexPathForSelectedRow
let cell = self.repliesTableView.cellForRow(at: indexPath!) as! ReplyCell
replyVC.replyQuote = cell.replyTextView.text
*/
}
}
}
发布于 2016-11-22 11:45:56
您需要使用协议,在Replycell.swift中,在类之前添加以下内容
protocol ReplycellDelegate: class {
func didPressButtonFromCell(cellView: Replycell, id: int)}
在类中添加以下内容
weak var delegate: ReplycellDelegate?
在单元格中的按钮操作中添加以下内容
delegate?.didPressButtonFromCell(cellView: self, id: 2)
现在在类ViewController中,在uitableview数据源之后添加RepplyCellDelegate,然后只调用函数didPressButtonFromCell
,Xcode将为您自动完成该函数,当按下单元格的按钮时将调用该函数,如果视图控制器中有单元格的内容,则向Repplycell类添加一个id变量,以便在创建每个单元格时将其传递给每个单元格,如果您在Replycell类中获得文本,而不是协议中的id,则声明一个字符串并将其发送给ViewController。
发布于 2016-11-22 08:12:31
试图获取文本值的方式并没有多大问题,您只是在错误的函数中这样做。UITableView有一个函数didSelectRowAt:indexPath
,它将在其中工作。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! Replycell
replyVC.replyQuote = cell.replyTextView.text
}
https://stackoverflow.com/questions/40746404
复制相似问题