ios - 使用单元格中的按钮来增加该特定单元格的值

标签 ios swift uitableview

如何增加特定单元格的值?

我看到了thisthis邮政。之前我无法开始工作(并且“脆弱”?),前者导致函数 incrementHandler()decrementHandler() 出现段错误。

class cell : UITableViewCell {
     @IBOutlet weak var counter: UILabel
     @IBAction func add (sender: AnyButton) {
          counter.text = String(Int(counter.text) + 1) 
          // find it's corresponding stat value (from other class) and update it
          stats[indexPath].counter = Int(counter.text)
     }
}


class tableView: UITableViewController {
    var stats = [Stat]()
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! ExpandedControllerCell
        let stat = stats[indexPath.row]
        cell.titleLabel.text = stat.name
        cell.bigCounterLabel.text = String(stat.counter)
        cell.smallCounterLabel.text = String(stat.counter)
        return cell
    }
}

最佳答案

在您的 cellForRowAtIndexPath 中,在按钮上设置一个标签。然后,在您的 IBAction 方法中,使用标记来确定点击了哪个单元格的按钮。增加数组中的一个值,然后告诉该 indexPath 处的单元重新加载自身。 (在 cellForRowAtIIndexPath 中,将计数器值安装到单元格中。)

您还可以编写按钮操作,以便它使用按钮的 frame.origin 来询问 TableView 按钮属于哪个单元格。这样更好,也更不容易脆弱。

查看我的回答 this thread了解如何执行此操作的说明。

关于ios - 使用单元格中的按钮来增加该特定单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064587/

相关文章:

ios - UISearchController 搜索栏文本在失去焦点时消失

ios - 如何从 vImage_Buffer 到 CVPixelBufferRef

objective-c - 从 UIViewController 导航返回时无法更新 UITableViewController 中的 TableCelView

ios - recaptcha 验证后的空白页使用电话号码 Swift 在 iOS 上使用 Firebase 进行身份验证

ios - 在 Swift 中收到新数据时返回新的 Cell

iphone - UITableViewCellStyleValue2 - 调整宽度?

iphone - Ios MFMailComposeViewController 不显示

ios - 为什么我只能在 TableView Swift 中展示我的第一部分?

ios - Swift 中的推送通知

ios - indexPathForRowAtPoint.row 始终为 tableView 中的每个单元格返回零