如何在另一个视图控制器Swift 4中向TableView插入数据?

时间:2018-03-08 05:03:19

标签: ios swift uitableview

我有ViewControllerAViewControllerB。我在ViewControllerB进行了网络通话,成功时,我想在TableView中向ViewControllerA插入数据,因此数据可以显示为TableView中的第1项}。

以下是我尝试的内容:

ViewControllerB

 var myItem = [Item]() //here is the array in ViewControllerA

Alamofire.request(MyURL!, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON{
            response in

            switch response.result{
            case .success(let result):

                let json = JSON(result)

                if let myJson = json.dictionary,let myItem = Item.init(dict: myJson){
                    self.myItem.insert(newPost, at: 0)
                    NotificationCenter.default.post(name: .reload, object: nil) //here I call notification center after insert to the array

                   self.dismiss(animated: true, completion: nil)
                   self.tabBarController?.selectedIndex = 0 //back to ViewControllerA
                }

            case .failure(let error):
                print("error = \(error)")
            }

        }

在ViewControllerA(包含tableView)

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(updateTableView), name: .reload, object: nil)
   }  

@objc func updateTableView(_ notification: Notification){
        print("here get called")
        self.tableView.reloadData()
    }

我为NotificationCenter

创建了一个扩展程序
extension Notification.Name {
    static let reload = Notification.Name("reloadTableView")
} 

完成所有这些操作后,我插入ViewControllerB数组的项目没有出现在TableView的{​​{1}}的第一位。

我在ViewControllerB函数中进行了打印,当updateTableView()中的NotificationCenter收到回复时会调用它,它会被调用,但数据不会出现。

我不能使用segue,因为两个ViewController都是TabbarController中的2个选项卡。

因此,在这种情况下,如何将ViewControllerA的数据插入ViewControllerB的{​​{1}}?

1 个答案:

答案 0 :(得分:2)

问题是你用这行创建一个新数组

NotificationCenter.default.post(name: .reload, object: self.myItem)

但viewControllerA使用不同的数组。尝试在通知中发送新数组

@objc func updateTableView(_ notification: Notification){
        var newItems = notification.object as! [Item]

        arrayOfControllerA.append(contentsOf: newItems)
        self.tableView.reloadData()
  }

然后在viewControllerA中设置新数组。

{{1}}