简体   繁体   English

创建后快速刷新TableView

[英]Swift Refresh TableView after creation

In swift I have two view controllers. 我有两个视图控制器。 One is a tableView and displays data from an array. 一个是tableView,它显示数组中的数据。 On a function call the other view controller calls the tableView and delivers arguments with new data for the table view. 在调用函数时,另一个视图控制器将调用tableView,并为表视图传递带有新数据的参数。 Even when I update the array buckets where the data is taken from the TableView doesn't update. 即使我更新了从TableView中获取数据的数组buckets ,也不会更新。 How do I get the program to reload its data? 如何获取程序以重新加载其数据?

TABLE VIEW 表格视图

import Foundation
import UIKit
class BucketTableViewController: UITableViewController {
    var buckets = ["A", "B", "C"]
    override func viewDidLoad() {
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return buckets.count
    } 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = buckets[indexPath.row]
        return cell
    }
    func updateBuckets(newBucket: NSArray) {
        buckets = newBucket as! [String]
        self.tableView?.reloadData()
    } 
}

I can verify that updateBuckets is called from the other view controller. 我可以验证是否从另一个视图控制器调用了updateBuckets。

OTHER VIEW CONTROLLER 其他视图控制器

    var bigArray = ["M", "A", "R", "C"]

override func viewDidLoad() {
    super.viewDidLoad()
    let buckets = BucketTableViewController()
    buckets.updateBuckets(bigArray)

}

Try using tableView?.beginUpdates() and tableView?.endUpdates() instead - I've found that tableView?.reloadData() can be finicky about data source updates sometimes. 尝试改用tableView?.beginUpdates()tableView?.endUpdates() -我发现tableView?.reloadData()有时对数据源更新有些挑剔。

Otherwise, make sure you're calling updateBuckets() on the right instance of BucketTableViewController() ; 否则,请确保在正确的BucketTableViewController()实例上调用updateBuckets() BucketTableViewController() it looks like you instantiated a new instance in your viewDidLoad() instead of changing the content of an existing instance (as you presumably would be doing). 好像您在viewDidLoad()中实例化了一个新实例,而不是更改现有实例的内容一样(可能会这样做)。

This line right here: 这行就在这里:

let buckets = BucketTableViewController()

You're creating a brand new BucketTableViewController instance and updating its buckets. 您正在创建一个全新的BucketTableViewController实例并更新其存储桶。 That's not going to cause the existing BucketTableViewController to update. 这不会导致现有的BucketTableViewController进行更新。 You need to figure out how to get a reference to the existing view controller and update it instead. 您需要弄清楚如何获取对现有视图控制器的引用并进行更新。

我会为您推荐与在此答案中所做的相同的事情: 从其他文件更新表视图-无法在没有参数的情况下调用'reloadData'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM