iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签 [英] iOS Swift, Update UITableView custom cell label outside of tableview CellForRow using tag

查看:125
本文介绍了iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置(Swift 1.2 / iOS 8.4):

Setup (Swift 1.2 / iOS 8.4):

我在UIViewController中有UITableView自定义单元格(标识符=单元格)。在自定义TableView单元格中有两个按钮(递增/递减计数)和一个标签(显示计数)。

I have UITableView custom cell (identifier = Cell) inside UIViewController. Have two buttons (increment/decrement count) and a label (display count) inside the custom TableView cell.

目标:

按下增加计数或减少计数按钮时更新标签。

Update the label as we press the increase count or decrease count button.

目前,我可以获取按钮Tag并调用CellForRowAtIndexPath之外的函数。按下按钮可增加和减少计数。但是我无法在标签中显示计数更新。

At present I am able to get the button Tag and call a function outside of the CellForRowAtIndexPath. The button press increases and decreases the count. But I am not able to display the count update in the label.

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

    let cell:FoodTypeTableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! FoodTypeTableViewCell

    cell.addBtn.tag = indexPath.row // Button 1
    cell.addBtn.addTarget(self, action: "addBtn:", forControlEvents: .TouchUpInside)

    cell.subBtn.tag = indexPath.row // Button 2
    cell.subBtn.addTarget(self, action: "subBtn:", forControlEvents: .TouchUpInside)

    cell.countLabel.text = // How can I update this label
    return cell
}

func addBtn(sender: AnyObject) -> Int {
    let button: UIButton = sender as! UIButton
    count = 1 + count
    println(count)
    return count
}

func subBtn(sender: AnyObject) -> Int {
    let button: UIButton = sender as! UIButton
    if count == 0 {
        println("Count zero")
    } else {
        count = count - 1
    }
    println(count)
    return count
}

我在这里和那里看过这个问题但是在Swift中无法找到明确的答案。我真的很感激,如果你能帮助清楚地回答它,以便其他人不能复制,但清楚地了解发生了什么。

I have seen this question here and there but was not able to find a clear answer in Swift. I would really appreciate if you could help answer it clearly so that other people can not just copy, but clearly understand what is going on.

谢谢。

推荐答案

这是一个不需要标签的解决方案。我不会完全按照你想要的方式重新创建单元格,但这涵盖了你要问的部分。

Here is a solution that doesn't require tags. I'm not going to recreate the cell exactly as you want, but this covers the part you are asking about.

使用Swift 2,因为我没有Xcode 6 .x了。

Using Swift 2 as I don't have Xcode 6.x anymore.

让我们从 UITableViewCell 子类开始。这只是一个标签的哑容器,上面有两个按钮。单元格实际上不执行任何特定的按钮操作,它只是将调用传递给配置方法中提供的闭包。这是MVC的一部分。视图不与模型交互,只与控制器交互。控制器提供闭包。

Let's start with the UITableViewCell subclass. This is just a dumb container for a label that has two buttons on it. The cell doesn't actually perform any specific button actions, it just passes on the call to closures that are provided in the configuration method. This is part of MVC. The view doesn't interact with the model, just the controller. And the controller provides the closures.

import UIKit

typealias ButtonHandler = (Cell) -> Void

class Cell: UITableViewCell {

    @IBOutlet private var label: UILabel!
    @IBOutlet private var addButton: UIButton!
    @IBOutlet private var subtractButton: UIButton!

    var incrementHandler: ButtonHandler?
    var decrementHandler: ButtonHandler?

    func configureWithValue(value: UInt, incrementHandler: ButtonHandler?, decrementHandler: ButtonHandler?) {
        label.text = String(value)
        self.incrementHandler = incrementHandler
        self.decrementHandler = decrementHandler
    }


    @IBAction func increment(sender: UIButton) {
        incrementHandler?(self)
    }


    @IBAction func decrement(sender: UIButton) {
        decrementHandler?(self)
    }
}

现在控制器就是这么简单

Now the controller is just as simple

import UIKit

class ViewController: UITableViewController {

    var data: [UInt] = Array(count: 20, repeatedValue: 0)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell

        cell.configureWithValue(data[indexPath.row], incrementHandler: incrementHandler(), decrementHandler: decrementHandler())

        return cell
    }

    private func incrementHandler() -> ButtonHandler {
        return { [unowned self] cell in
            guard let row = self.tableView.indexPathForCell(cell)?.row else { return }
            self.data[row] = self.data[row] + UInt(1)

            self.reloadCellAtRow(row)
        }
    }

    private func decrementHandler() -> ButtonHandler {
        return { [unowned self] cell in
            guard
                let row = self.tableView.indexPathForCell(cell)?.row
                where self.data[row] > 0
                else { return }
            self.data[row] = self.data[row] - UInt(1)

            self.reloadCellAtRow(row)
        }
    }

    private func reloadCellAtRow(row: Int) {
        let indexPath = NSIndexPath(forRow: row, inSection: 0)

        tableView.beginUpdates()
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        tableView.endUpdates()
    }

}

当单元格出列时,它会使用要在标签中显示的值配置单元格,并提供处理按钮操作的闭包。这些控制器与模型交互,以递增和递减显示的值。更改模型后,它会在tableview中重新加载更改的单元格。

When the cell is dequeued, it configures the cell with the value to show in the label and provides the closures that handle the button actions. These controllers are what interact with the model to increment and decrement the values that are being displayed. After changing the model, it reloads the changed cell in the tableview.

闭包方法采用单个参数,对单元格的引用,从中可以找到细胞的一排。这比使用标签更加去耦合,这对于了解tableview中单元格的索引是一个非常脆弱的解决方案。

The closure methods take a single parameter, a reference to the cell, and from this it can find the row of the cell. This is a lot more de-coupled than using tags, which are a very brittle solution to knowing the index of a cell in a tableview.

您可以下载完整的工作示例(需要Xcode7)来自 https://bitbucket.org/abizern/so-32931731/get/ce31699d92a5。 zip

You can download a full working example (Requires Xcode7) from https://bitbucket.org/abizern/so-32931731/get/ce31699d92a5.zip

这篇关于iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆