ios - 点击表格 View 中的按钮 - 错误的单元格

标签 ios swift uitableview uiviewcontroller segue

您好,当我单击单元格中的按钮时,我试图在单元格中传递一个变量,该变量是标签。但问题是每次当我将代码放入 cellForRowAtIndexPath 时,它每次都会从错误的单元格中获取标签。为什么以及如何解决这个问题?

var variableToPass: String!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

    variableToPass = label1.text

    cell.label1.userInteractionEnabled = true
    let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
    cell.label1.addGestureRecognizer(tapButton)

    return cell as MainCell
}

func tapButton(sender:UITapGestureRecognizer) {
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SegueIdentifierName" {
        let viewController = segue.destinationViewController as! ViewController
        viewController.getVariablePassed = variableToPass
    }
}

最佳答案

您的代码设置方式,variableToPass 始终是从 dequeueReusableCellWithIdentifier 获取的最后一个单元格中的文本。相反,在您的 tapButton 方法中设置 variableToPass,因为这样您就知道选择了哪个单元格并且您可以正确设置 variableToPass:

func tapButton(sender:UITapGestureRecognizer) {
    let label = sender.view as! UILabel
    self.variableToPass = label.text
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

关于ios - 点击表格 View 中的按钮 - 错误的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924688/

相关文章:

ios - 回到 ViewController 时委派丢失

ios - 更改 DetailViewController Swift 中的数据

ios - 可以从我自己的应用程序发送 Facebook 好友请求吗?

ios - 为什么 iOS UIWebView 的 loadRequest 方法没有返回值?

ios - 无法使用 Share Extension 和 AFNetworking Cocoapod 存档构建

ios - 当用户在 swift ios 中选择 tableview 行时显示复选标记

ios - 如何在编辑表单时显示预先检查的 UITableViewCells。

objective-c - 在 Objective C 中绘制带有渐变的图表

ios - 如何使用 ios-charts 制作分组条形图?

json - 如何从 nsdictionary swift 获取数组