ios - 如何将单元格编号发送到 TableViewCell 中的函数

标签 ios swift

我想知道如何在下面的tapPickView 函数中获取单元格number(indexPath.row)topViewUITableViewCell上,pickViewtopView上。如果 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
}

在填充单元格时,您可以将 pickViewtag 值设置为 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/

相关文章:

xcode - 如何在命令行工具中使用 'SQLite'(github 上的包装器)?

ios - 我可以在 watchkit 的 map 上添加按钮吗?

ios - 如何在 Swift 中使用 SnapKit 使 UIView 具有相同的宽度和高度?

ios - 如果按得太久,快速长按将停止工作

swift - Swift 5 编译器有时不调用子类中的委托(delegate)方法

ios - 如何使 UITableView 并发?

ios - 更改 Coreplot 图形的刻度标签

ios - 如何限制 UITableViewController 中的多选

ios - 在 Objective-C iOS 中将内容上传到 FTP

归一化手指触摸数据的算法(减少点数)