ios - Swift 从 UITableViewCell 中删除存储在 UITableViewController 中的数据

标签 ios swift uitableview

我有一个自定义类,它扩展了 UIViewController 并包含一个 TableView ,以及一个存储填充 TableView 的数据的数组。对于我的自定义单元格,我有一个按钮,当按下该按钮时,应该从表格 View 中删除该单元格。但是,我无法找到一种方法来从 TableView Controller 中的数组中删除数据并从单元格的类中重新加载数据。我在类似帖子上看到的一些答案建议通知或委托(delegate),但由于我的应用程序(选项卡 Controller )的结构以及我已经将通知用于另一个功能,前者效率低下,我不知道如何在这种情况下使用后者。 这是自定义单元类的代码:

class CustomCell: UITableViewCell {
    @IBOutlet var label: UILabel!
    @IBOutlet var removeButton: UIButton!

    @IBAction func remove(sender: AnyObject) {
        // don't know what to put here
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
         super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

这是 TableView Controller 类:

class CustomController: UIViewController, UITableViewDataSource {
    @IBOutlet var table: UITableView!

    var data: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        table.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
        // put content in
        return cell
    }
}

数组data是我想从CustomCell中的remove访问的。我得到的最接近的是在 CustomCell 中使用 self.superview.superview.superview,它返回 CustomController 控制的 View 。但是,如果不实例化一个新的实例,我无法获取 CustomController 的实例。如何从 CustomCell 类修改 CustomController 中的变量?

最佳答案

在你的自定义单元格中添加这个

class CustomCell: UITableViewCell {
 var customControllerReference: CustomController?
}

然后在 cellForRowAtIndexPath 中的自定义 Controller 中添加此内容

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
        cell.customControllerReference = self
        return cell
    }

关于ios - Swift 从 UITableViewCell 中删除存储在 UITableViewController 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073058/

相关文章:

ios - UITableViewCell展开动画?

ios - 无法显示我的自定义 UITableViewCell

ios - 无法在 SwiftUI 列表中更改 LPLinkView 的帧大小

ios - 导入什么以在 iOS 中使用 Facebook Graph API?

ios - Firebase 通知在 Testflight 上不起作用

ios - 将选择器从 UIViewController 传递到 UIView

ios - 相机预览未填满屏幕

swift - 如何使用完成处理程序编写自定义函数?

swift - 在 swift 中捕获闭包的值是否意味着创建静态变量?

ios - 在 Swift 中将字符串传递回之前的 View Controller 时遇到困难