How to reload tableview after delete item in cell Swift 2

假如想象 提交于 2019-12-06 04:05:10

You can try this way, add a NSNotificationCenter in your ViewController viewDidLoad

NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData:",name:"reloadData", object: nil)

And then a its selector, means function

func reloadData(notification:NSNotification){
    // reload function here, so when called it will reload the tableView
    self.TableView.reloadData()
}

After both the above had been added in your viewController, now you need to call/fire this notification to reload your TableView. So inside your btnDelete clicked,

@IBAction func btnDeletar(sender: AnyObject) {
    print(btnDeletar.titleLabel?.text)
    if (bdAccount.indexOf((btnDeletar.titleLabel?.text)!) != nil) {
        print(bdAccount.indexOf((btnDeletar.titleLabel?.text)!))
        bdAccount.removeAtIndex(bdAccount.indexOf((btnDeletar.titleLabel?.text)!)!)
        bdAccount.sortInPlace()


        // This will fire the Notification in your view controller and do the reload.
        NSNotificationCenter.defaultCenter().postNotificationName("reloadData",object: self)

    }
}

If your tableView uses the bdAccount array as input for the amount of sections, row and the data for cellForRowAtIndexPath than it is just that.

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

    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return bdAccount.count
}

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

    // Configure the cell...
    cell.textlabel?.text = bdAccount.labelText // or something like that

    return cell
}

If you now call the tableView.reloadData() method it will reload the entire tableView and since it is based on your array where you just deleted one entity, that entity will also have disappeared from the tableView.

You can use

guard let index = bdAccount.indexOf(btnDeletar.titleLabel!.text) else {
    return
}

instead if (bdAccount.indexOf((btnDeletar.titleLabel?.text)!) != nil)

To remove just a row you need to store index path for cell. Add a indexPath property.

After your cell know about it's index path and table view, you have all parameters to call tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!