Reference from UITableViewCell to parent UITableView?

前端 未结 7 1688
有刺的猬
有刺的猬 2020-11-29 04:02

Is there any way to access the owning UITableView from within a UITableViewCell?

相关标签:
7条回答
  • 2020-11-29 05:06

    Xcode 7 beta, Swift 2.0

    This works fine for me, in my opinion it has nothing to do with the hierarchy or whatever. I had no trouble with this approach so far. I've used this for many async callbacks (ex. when an API request is done).

    TableViewCell class

    class ItemCell: UITableViewCell {
    
        var updateCallback : ((updateList: Bool)-> Void)? //add this extra var
    
        @IBAction func btnDelete_Click(sender: AnyObject) {
            let localStorage = LocalStorage()
            if let description = lblItemDescription.text
            {
                //I delete it here, but could be done at other class as well.
                localStorage.DeleteItem(description) 
            }
            updateCallback?(updateList : true)
    
        }
    }
    

    Inside table view class that implements the DataSource and Delegate

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: ItemCell = self.ItemTableView.dequeueReusableCellWithIdentifier("ItemCell") as! ItemCell!
        cell.updateCallback = UpdateCallback //add this extra line
        cell.lblItemDescription?.text = self.SomeList[indexPath.row].Description
        return cell
    }
    
    func UpdateCallback(updateTable : Bool) //add this extra method
    {
        licensePlatesList = localStorage.LoadNotificationPlates()
        LicenseTableView.reloadData()
    }
    

    Ofcourse you can put any variable in the updateCallback and change it's function in the tableView accordingly.

    Someone might want to tell me if it is save to use though, just to be sure.

    0 讨论(0)
提交回复
热议问题