CustomTableView 从不更新

CustomTableView never updates

此代码假设从 JSON 对象获取数据然后用它更新 table 的行,所以我使用了 (tableView.reloaddata) 但它不起作用。

class history: UIViewController,UITableViewDataSource,UITableViewDelegate {
    var rec = [recs]()
    var delegate2 : historyViewControllerProtocol!
    var ID2 = [String]()
    var Amount2 = [String]()
    var Desc2 = [String]()
    var records:String = ""

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        reciptshistory(){ (boolValue) -> () in
            self.Loaddata()
            self.tableView.reloadData()
                   }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func reciptshistory(completion: @escaping (_ result: Bool)->())
    {

        var Buffer : String
        Buffer = "userID=" + userID

        print("intial///////////////////" + Buffer + "//////////////End")

        let url:NSURL = NSURL(string: "http://nh75.com.kw/old-soon/Paynet/recipthistory.php")!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        let data = Buffer.data(using: String.Encoding.utf8)
        let task = session.uploadTask(with: request as URLRequest, from: data, completionHandler:
            {(data,response,error) in


                guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
                    print("error")
                    return
                }

                let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                print(dataString as Any)
                self.records = dataString!;


                if(self.records == "X")
                {
                    print("No records");
                    completion (true)

                } else {
                    print (dataString! )
                    do {
                        // let data = dataString?.data(using: .utf8)
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
                        if let result = json["result"] as? [[String: AnyObject]] {
                            for blog in result {
                                if let iD = blog["id"] as? String {
                                    if let amount = blog["Amount"] as? String {
                                        if let desc = blog["Desc"] as? String {
                                            self.ID2.append(iD)
                                            self.Amount2.append(amount)
                                            self.Desc2.append(desc)
                                            //recipt.text = self.ID
                                            //print(ID , Amount , Desc)
                                        }
                                    }
                                }
                            }
                            completion (true)
                        }
                    }catch {
                        print("error serializing JSON: \(error)")
                    }
                }





        }


        );
        task.resume()
    }


    func Loaddata()
    {
         DispatchQueue.main.async {
     if(self.records == "X")
     {

                let alert = UIAlertController(
                    title: "No Records found",
                    message: "No records found for you",
                    preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { (test) -> Void in
                    self.dismiss(animated: true, completion: nil)
                }))

                self.present(
                    alert,
                    animated: true,
                    completion: nil)




     }else{

        for L in 0..<self.ID2.count{
                self.rec += [recs(reciptsnum: self.ID2[L] , amount:self.Amount2[L] , descript: self.Desc2[L])!]
        }
        }
        }
        }





    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }



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

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "RecTableViewCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RecTableViewCell
        // Fetches the appropriate meal for the data source layout.

        let recc = rec[(indexPath as NSIndexPath).row]
        cell.reciptnum.text = recc.reciptsnum
        cell.Amount.text = recc.amount
        cell.descript.text = recc.descript
        return cell

    }

每次我 运行 应用程序时,自定义 table 视图都是空的,请指教... here is a screenshot of the app running

在我看来,您的控制器没有作为委托和数据源连接到您的 table。如果您在情节提要中将其设置为 'UITableViewController' 而不是 'UIViewController'(并将 'history' 的子类设置为 UITableViewController),它应该会自动连接。

您还可以在代码中连接:

tableView.delegate=自己 tableView.datasource=自己

但您仍然可能需要子类化为 UITableViewController 而不是 UIViewController。

一些尝试:

将 TableView 委托和数据源设置为自身

在 Storyboard 上设置 Cell 重用标识符

确保在table重新加载时正确拉取数据并且数组不为空

我已经按照@Gagan_IOS 的建议更新了代码,它工作得很好......

reciptshistory(){ (boolValue) -> () in
    self.Loaddata()
    DispatchQueue.main.async {
    self.tableView.reloadData()
    }

谢谢