当前位置: 首页 > 知识库问答 >
问题:

在细节视图上完成删除操作后更新或重新加载UITableView

艾学海
2023-03-14

我有一个uitableview,它通过json从mysql收集数据。然后它有一个细节视图,该视图有两个操作“编辑”和“删除”。编辑工作很好。删除操作删除mysql数据,但问题是它不会从uitableview更新数据。

这是屏幕截图和代码

//表视图控制器

import UIKit

class TableViewController: UITableViewController {

    var storeList = [Store]()

    //var storeList:Store?


    override func viewDidLoad() {
        super.viewDidLoad()

        /*
        if let s = storeList
        {
            txtName.text = s.storeName
        }
*/


        // Uncomment the following line to preserve selection between presentations
         //self.clearsSelectionOnViewWillAppear = true

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        self.loadRecords()
        self.tableView.reloadData()


    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData() // to reload selected cell

        //tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }








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

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return storeList.count
    }


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

        // Configure the cell...

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StoreTVC



        let s = storeList[indexPath.row] as Store

        cell.lblName.text = s.storeName
        //cell.lblID.text = s.storeId


        return cell
    }

    // for swipe delete

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            storeList.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }




    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */


    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        /*

        if segue.identifier == "details"
        {

        //if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)

            if let indexPath = tableView.indexPathForSelectedRow
            {
                let s = storeList[indexPath.row] as Store

                let dvc = segue.destinationViewController as! ViewDetails

                dvc.store = s
            }

        }
*/

        if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
        {
            let s = storeList[indexPath.row] as Store

            let dvc = segue.destinationViewController as! ViewDetails

            dvc.store = s
        }


    }


    func loadRecords()
    {
        //The address of the web service
        let urlString = "http://localhost/crud/read_for_table_view.php"

        // 1 - Create the session by getting the configuration and then crrating the session

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)

        //2 - Create the URL Object

        if let url = NSURL(string: urlString)
        {
            //3 - Create the request object

            let request = NSURLRequest(URL: url)

            //4 - execute the request

            let taskData = session.dataTaskWithRequest(request, completionHandler: {
                (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in

                //5 - Do something with the Data back

                if(data != nil)
                {
                    //we got some data back

                    print("\(data)")
                    /*
                    var  parseError:NSError?

                    let parsedStores = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as! NSDictionary
                    */

                    do {
                        if let parsedStores = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                            print("Json Data \n \(parsedStores)")

                            if let stores:AnyObject = parsedStores["result"]
                            {
                                self.parseJSON(stores)
                            }
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }



                }else
                {
                    //we got an error
                    print("Error getting stores :\(error!.localizedDescription)")
                }
            })

            taskData.resume()

        }

    }

    func parseJSON(jsonData:AnyObject)
    {
        if let storeData = jsonData as? [[NSObject:AnyObject]]
        {
            var store:Store

            //we loop through all the recors and everytime we create
            // an object of kind store and then add to the store list

            for s in storeData
            {
                store = Store()
                // this part is getting the values

                if let sId:AnyObject = s["id"]
                {
                    if let storeID = sId as? String
                    {
                        print("Store id = \(storeID)")
                        store.storeId = storeID
                    }
                }

                if let sn:AnyObject = s["name"]
                {
                    if let storeName = sn as? String
                    {
                        store.storeName = storeName

                    }
                }


                storeList += [store]
            }


            NSOperationQueue.mainQueue().addOperationWithBlock()
                {

                    self.tableView.reloadData()
            }
        }
    }


}

//详细视图

import UIKit

class TableViewController: UITableViewController {

    var storeList = [Store]()

    //var storeList:Store?


    override func viewDidLoad() {
        super.viewDidLoad()

        /*
        if let s = storeList
        {
            txtName.text = s.storeName
        }
*/


        // Uncomment the following line to preserve selection between presentations
         //self.clearsSelectionOnViewWillAppear = true

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        self.loadRecords()
        self.tableView.reloadData()


    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData() // to reload selected cell

        //tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }








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

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return storeList.count
    }


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

        // Configure the cell...

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StoreTVC



        let s = storeList[indexPath.row] as Store

        cell.lblName.text = s.storeName
        //cell.lblID.text = s.storeId


        return cell
    }

    // for swipe delete

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            storeList.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }




    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */


    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        /*

        if segue.identifier == "details"
        {

        //if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)

            if let indexPath = tableView.indexPathForSelectedRow
            {
                let s = storeList[indexPath.row] as Store

                let dvc = segue.destinationViewController as! ViewDetails

                dvc.store = s
            }

        }
*/

        if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
        {
            let s = storeList[indexPath.row] as Store

            let dvc = segue.destinationViewController as! ViewDetails

            dvc.store = s
        }


    }


    func loadRecords()
    {
        //The address of the web service
        let urlString = "http://localhost/crud/read_for_table_view.php"

        // 1 - Create the session by getting the configuration and then crrating the session

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)

        //2 - Create the URL Object

        if let url = NSURL(string: urlString)
        {
            //3 - Create the request object

            let request = NSURLRequest(URL: url)

            //4 - execute the request

            let taskData = session.dataTaskWithRequest(request, completionHandler: {
                (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in

                //5 - Do something with the Data back

                if(data != nil)
                {
                    //we got some data back

                    print("\(data)")
                    /*
                    var  parseError:NSError?

                    let parsedStores = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as! NSDictionary
                    */

                    do {
                        if let parsedStores = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                            print("Json Data \n \(parsedStores)")

                            if let stores:AnyObject = parsedStores["result"]
                            {
                                self.parseJSON(stores)
                            }
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }



                }else
                {
                    //we got an error
                    print("Error getting stores :\(error!.localizedDescription)")
                }
            })

            taskData.resume()

        }

    }

    func parseJSON(jsonData:AnyObject)
    {
        if let storeData = jsonData as? [[NSObject:AnyObject]]
        {
            var store:Store

            //we loop through all the recors and everytime we create
            // an object of kind store and then add to the store list

            for s in storeData
            {
                store = Store()
                // this part is getting the values

                if let sId:AnyObject = s["id"]
                {
                    if let storeID = sId as? String
                    {
                        print("Store id = \(storeID)")
                        store.storeId = storeID
                    }
                }

                if let sn:AnyObject = s["name"]
                {
                    if let storeName = sn as? String
                    {
                        store.storeName = storeName

                    }
                }


                storeList += [store]
            }


            NSOperationQueue.mainQueue().addOperationWithBlock()
                {

                    self.tableView.reloadData()
            }
        }
    }


}

你能帮忙吗?

共有3个答案

羿易安
2023-03-14

请尝试以下代码

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        storeList.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.loadRecords()
    }
}

希望这对你有帮助

穆轶
2023-03-14

这里是更好的解决方案,而不是在viewWillEmerar中的reloadtableview。使用委托的方法。

在详图视图控制器上添加。

weak var delegate : TableViewController!

修改表视图控制器上的代码行

if segue.identifier == "details"{
    if let indexPath = tableView.indexPathForSelectedRow{
      let s = storeList[indexPath.row] as Store
      let dvc = segue.destinationViewController as! ViewDetails
      dvc.store = s
      dvc.delegate = self
    }
}

在详细信息视图上完成操作时,或在关闭详细信息视图之前。在详图视图中执行以下行。

self.delegate.tableView.reloadData()

在这里,我希望这是更好的方法和最佳实践,而不是你的方法。试试看。:)

袁玮
2023-03-14

所以我得到了答案。

这是最新消息

import UIKit

class TableViewController: UITableViewController {

    var storeList = [Store]()

    //var storeList:Store?


    override func viewDidLoad() {
        super.viewDidLoad()

        /*
        if let s = storeList
        {
            txtName.text = s.storeName
        }
*/


        // Uncomment the following line to preserve selection between presentations
         //self.clearsSelectionOnViewWillAppear = true

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        self.loadRecords()
        self.tableView.reloadData()


    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.loadRecords() // to reload selected cell

        //tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }








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

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return storeList.count
    }


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

        // Configure the cell...

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StoreTVC



        let s = storeList[indexPath.row] as Store

        cell.lblName.text = s.storeName
        //cell.lblID.text = s.storeId


        return cell
    }

    // for swipe delete

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            storeList.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }




    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */


    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        /*

        if segue.identifier == "details"
        {

        //if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)

            if let indexPath = tableView.indexPathForSelectedRow
            {
                let s = storeList[indexPath.row] as Store

                let dvc = segue.destinationViewController as! ViewDetails

                dvc.store = s
            }

        }
*/

        if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
        {
            let s = storeList[indexPath.row] as Store

            let dvc = segue.destinationViewController as! ViewDetails

            dvc.store = s
        }


    }


    func loadRecords()
    {
        //The address of the web service
        let urlString = "http://localhost/crud/read_for_table_view.php"

        // 1 - Create the session by getting the configuration and then crrating the session

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)

        //2 - Create the URL Object

        if let url = NSURL(string: urlString)
        {
            //3 - Create the request object

            let request = NSURLRequest(URL: url)

            //4 - execute the request

            let taskData = session.dataTaskWithRequest(request, completionHandler: {
                (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in

                //5 - Do something with the Data back

                if(data != nil)
                {
                    //we got some data back

                    print("\(data)")
                    /*
                    var  parseError:NSError?

                    let parsedStores = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as! NSDictionary
                    */

                    do {
                        if let parsedStores = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                            print("Json Data \n \(parsedStores)")

                            if let stores:AnyObject = parsedStores["result"]
                            {
                                self.parseJSON(stores)
                            }
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }



                }else
                {
                    //we got an error
                    print("Error getting stores :\(error!.localizedDescription)")
                }
            })

            taskData.resume()

        }

    }

    func parseJSON(jsonData:AnyObject)
    {
        storeList.removeAll()

        if let storeData = jsonData as? [[NSObject:AnyObject]]
        {
            var store:Store

            //we loop through all the recors and everytime we create
            // an object of kind store and then add to the store list

            for s in storeData
            {
                store = Store()
                // this part is getting the values

                if let sId:AnyObject = s["id"]
                {
                    if let storeID = sId as? String
                    {
                        print("Store id = \(storeID)")
                        store.storeId = storeID
                    }
                }

                if let sn:AnyObject = s["name"]
                {
                    if let storeName = sn as? String
                    {
                        store.storeName = storeName

                    }
                }


                storeList += [store]
            }


            NSOperationQueue.mainQueue().addOperationWithBlock()
                {

                    self.tableView.reloadData()
            }
        }
    }


}

 类似资料:
  • 我有一个由Access DB使用ResultSet&填充的JTable。我有一个方法可以正确地从数据库中删除记录,但在刷新表模型的当前视图时遇到了困难。我看过类似的帖子,并尝试使用和,但没有成功。我还注意到其他帖子提到了的使用,因为它有add/remove行方法,但我使用的代码来自我去年使用的Java教科书(教授从未达到这一点,所以我试图自己学习)... 以下是定制JFrame的类: 下面是Abs

  • 问题内容: 我正在尝试转学;为此,我想删除神经网络的最后两层并添加另外两层。这是一个示例代码,它也会输出相同的错误。 我使用删除了该图层,但是当我尝试添加其输出时出现此错误 AttributeError:“模型”对象没有属性“添加” 我知道该错误的最可能原因是不当使用。我应该使用其他什么语法? 编辑: 我试图在keras中删除/添加图层,但不允许在加载外部重物后添加它。 它显示此错误 问题答案:

  • 我尝试在从KieBase中删除规则后重新创建KieSession,但删除的规则仍在触发。 我使用以下代码创建了一个KieBase并删除了一条规则: 但是当我根据ksesion1评估一个事实时,rule1仍然在触发。如何将编辑后的KieBase重新加载到新会话中?

  • 我使用的刀片是伟大的,但缩小是,必须重新编译和html文件创建。 因此,在开发阶段,我需要了解如何在每次页面重新加载时删除存储视图中的所有文件。 知道easies php代码是什么吗?我应该把它放在哪里?在基本控制器中?在文件服务器或路由中。php? 谢谢你的任何想法。我卡住了,需要一些建议,在哪里把删除代码,所以它不删除后,刀片编译为html文件在存储/视图。

  • 问题内容: 我知道这很长,但是我需要在主要问题之前提供一些背景信息。我正在创建一个页面,该页面将分为两列。这是ui路由器代码: 基本上,用户将过渡到状态,该状态具有如下所示的模板: 将为用户显示两列。左列仅具有一个输入字段和按钮,按下该按钮会将用户转换到状态。 当我们转换到状态时,其控制器将调用,这将在右列中设置其嵌套视图。该状态将首先以随机顺序解析数字数组,然后将其作为参数传入控制器。所述然后部

  • 我有一项服务,每天在Kubernetes上部署数千个短期工作。我试图让Kubernetes在完成后使用这里描述的功能删除这些作业: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#clean-up-finished-jobs-automatically 作业完成,但在表示的时间限制之