iOS Swift, Update UITableView custom cell label outside of tableview CellForRow using tag

前端 未结 3 1448
一整个雨季
一整个雨季 2020-12-28 11:07

Setup (Swift 1.2 / iOS 8.4):

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

3条回答
  •  梦毁少年i
    2020-12-28 11:37

    Use tableView.reloadData() to reload your tableView content each time you click a button.

    let text = "something"
     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 = something
        return cell
    }
    
    func addBtn(sender: AnyObject) -> Int {
        let button: UIButton = sender as! UIButton
        count = 1 + count
        println(count)
        something = "\(count)"
        self.tableView.reloadData()
        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)
        something = "\(count)"
        self.tableView.reloadData()
        return count
    }
    

    Update1

    After your comments ... you have an array (one value for each food) like this, and whenever you click on a button, you take the index of the row the contains that button, then use that index to retrive the value of count from your array, then reload the table view content.

提交回复
热议问题