我想知道如何在下面的tapPickView
函数中获取单元格number(indexPath.row)
。 topView
在UITableViewCell
上,pickView
在topView
上。如果 pickView
被点击,tapPickView
被激活。
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
"QuestionAndAnswerReuseIdentifier",
forIndexPath: indexPath) as! QuestionAndAnswerTableViewCell
cell.topView.pickView.userInteractionEnabled = true
var tap = UITapGestureRecognizer(target: self, action: "tapPickView")
cell.topView.pickView.addGestureRecognizer(tap)
return cell
}
func tapPickView() {
answerQuestionView = AnswerQuestionView()
answerQuestionView.questionID = Array[/*I wanna put cell number here*/]
self.view.addSubview(answerQuestionView)
}
最佳答案
首先,您需要在添加手势识别器时将 :
符号附加到您的选择器,以便它获得 pickView
作为其参数。
var tap = UITapGestureRecognizer(target: self, action: "tapPickView:")
除此之外,单元格是可重复使用的对象,因此您应该通过删除之前添加的手势来防止一次又一次地向同一 View 实例添加相同的手势。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("QuestionAndAnswerReuseIdentifier", forIndexPath: indexPath) as! QuestionAndAnswerTableViewCell
cell.topView.pickView.userInteractionEnabled = true
cell.topView.pickView.tag = indexPath.row
for recognizer in cell.topView.pickView.gestureRecognizers ?? [] {
cell.topView.pickView.removeGestureRecognizer(recognizer)
}
cell.topView.pickView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapPickView:"))
return cell
}
在填充单元格时,您可以将 pickView
的 tag
值设置为 indexPath.row
,这样您就可以通过 轻松查询它>cellForRowAtIndexPath(_:)
。
cell.topView.pickView.tag = indexPath.row
假设您已经知道您点击的单元格部分。假设它是 0。
func tapPickView(recognizer: UIGestureRecognizer) {
let indexPath = NSIndexPath(forRow: recognizer.view.tag, inSection: 0)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
print("You tapped on \(cell)")
}
}
希望这对您有所帮助。
关于ios - 如何将单元格编号发送到 TableViewCell 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31447227/