【发布时间】:2016-07-18 16:46:25
【问题描述】:
我的TableView 具有自定义单元格,其中有一个按钮可以在另一个视图中显示相应的详细信息。
这个线程让我开始了,我尝试使用customCell 中的委托来实现该方法:
How to access the content of a custom cell in swift using button tag?
我想要实现的是,当我单击按钮时,它会读取单元格的名称并将其传递给下一个控制器。但是似乎我无法使用委托方法传递名称,其字段为nil。
点击按钮时如何获取单元格的具体内容?
这是我到目前为止所做的:
在创建自己的单元格的类中,我设置了委托:
protocol CustomCellDelegate {
func cellButtonTapped(cell: DemoCell)
}
(........)
var delegate: CustomCellDelegate?
@IBAction func buttonTapped(sender: AnyObject) {
delegate?.cellButtonTapped(self)
}
在TableViewController 我有以下内容:
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCellWithIdentifier("FoldingCell",
forIndexPath: indexPath) as! DemoCell
cell.delegate = self
//TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer
let resultList = self.items["result"] as! [[String: AnyObject]]
let itemForThisRow = resultList[indexPath.row]
cell.schoolNameClosedCell.text = itemForThisRow["name"] as! String
cell.schoolNameOpenedCell.text = itemForThisRow["name"] as! String
self.schoolIdHelperField = itemForThisRow["name"] as! String
cell.schoolIntroText.text = itemForThisRow["name"] as! String
//call method when button inside cell is tapped
cell.innerCellButton.addTarget(self, action: #selector(MainTableViewController.cellButtonTapped(_:)), forControlEvents: .TouchUpInside)
cell.school_id = itemForThisRow["name"] as! String
// cell.schoolIntroText.text = "We from xx University..."
return cell
}
最后是单击单元格内按钮时的目标方法
func cellButtonTapped(cell: DemoCell) {
print("the school id: ")
print(cell.schoolNameOpenedCell) //this line throws an error EXC_BAD_ACCESS 0x0
}
【问题讨论】:
标签: ios swift uibutton tableview custom-cell