Segue 传递数据后如何重新加载 tableView 数据

2024-01-11

我有两个表视图。一种是用户单击的,另一种是显示数据的。当用户单击第一个表视图中的单元格时,将对我的 firebase 数据库进行查询,并将查询存储在数组中。然后我通过 segue 传递数据。我使用了属性观察器,因此我知道正在设置变量。通过使用断点,我能够确定我的变量在 cellForRowAtIndexPath 方法之前获取其值。我需要帮助在表视图中显示数据。我不知道在哪里重新加载数据以使表视图更新我的数据。我正在使用斯威夫特。

编辑2:我已经解决了我的问题。我将发布我的第一个和第二个表视图,以便您可以看到我的解决方案。

第一个表视图

import UIKit
import Firebase
import FirebaseDatabase

class GenreTableViewController: UITableViewController {

let dataBase = FIRDatabase.database()

var genreArray = ["Drama","Classic,Comic/Graphic novel","Crime/Detective","Fable,Fairy tale","Fantasy","Fiction narrative", "Fiction in verse","Folklore","Historical fiction","Horror","Humour","Legend","Magical realism","Metafiction","Mystery","Mythology","Mythopoeia","Realistic fiction","Science fiction","Short story","Suspense/Thriller","Tall tale","Western,Biography","Autobiography","Essay","Narrative nonfiction/Personal narrative","Memoir","Speech","Textbook","Reference book","Self-help book","Journalism", "Religon"]

var ResultArray: [NSObject] = []
var infoArray:[AnyObject] = [] 

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

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

// 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 genreArray.count
}

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

    // Configure the cell...

    cell.textLabel?.text = genreArray[indexPath.row]

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let DestViewController: ResultTableViewController = segue.destinationViewController as! ResultTableViewController

    if segue.identifier == "letsGo" {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            let tappedItem = self.genreArray[indexPath.row]
            DestViewController.someString = tappedItem 
        }  
    }
}

}

import UIKit
import Firebase
import FirebaseDatabase

class ResultTableViewController: UITableViewController {


let dataBase = FIRDatabase.database()
var SecondResultArray: [FIRDataSnapshot]! = []
var someString: String?{
    didSet {
      print("I AM A LARGE TEXT")
      print(someString)
    }
}

override func viewDidLoad() {

    let bookRef = dataBase.reference().child("books")

    bookRef.queryOrderedByChild("Genre")
        .queryEqualToValue(someString)
        .observeSingleEventOfType(.Value, withBlock:{ snapshot in
            for child in snapshot.children {

                self.SecondResultArray.append(child as! FIRDataSnapshot)
                //print(self.ResultArray)
            }

            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()
            }

        })

    super.viewDidLoad()

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

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

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 SecondResultArray.count
}

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

    // Configure the cell...

    let bookSnapShot: FIRDataSnapshot! = self.SecondResultArray[indexPath.row]

    let book = bookSnapShot.value as! Dictionary<String, String>

    let Author = book["Author"] as String!
    let Comment = book["Comment"] as String!
    let Genre = book["Genre"] as String!
    let User = book["User"] as String!
    let title = book["title"] as String!

    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping

    cell.textLabel?.text = "Author: " + Author + "\n" + "Comment: " + Comment + "\n" + "Genre: " + Genre + "\n" + "User: " + User + "\n" +  "Title: " + title

    let photoUrl = book["bookPhoto"], url = NSURL(string:photoUrl!), data = NSData(contentsOfURL: url!)
        cell.imageView?.image = UIImage(data: data!)

    return cell
}

}

为了更好的上下文和故障排除,这里是我当前应该显示数据的 tableView 代码:

    import UIKit

    class ResultTableViewController: UITableViewController {

        var SecondResultArray: Array<NSObject> = []{
            willSet(newVal){ 
                print("The old value was \(SecondResultArray) and the new value is \(newVal)")
            }
            didSet(oldVal){
               print("The old value was \(oldVal) and the new value is \(SecondResultArray)")
               self.tableView.reloadData()        
            }
        }
        override func viewDidLoad() {
            print ("I have this many elements\(SecondResultArray.count)")
            super.viewDidLoad()
        }
        // 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 SecondResultArray.count
        }

        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)
            cell.textLabel?.text = SecondResultArray[indexPath.row] as? String
            return cell
        }
    }

Edit:

这是我的第一个表视图控制器。我尝试过使用完成处理程序,但无法正确调用它,而且我的查询发生在 didSelectRowAtIndexPath 方法中这一事实使我感到受限。请帮忙。

import UIKit
import Firebase
import FirebaseDatabase

class GenreTableViewController: UITableViewController {


    let dataBase = FIRDatabase.database()

    var genreArray = ["Drama","Classic,Comic/Graphic novel","Crime/Detective","Fable,Fairy tale","Fantasy","Fiction narrative", "Fiction in verse","Folklore","Historical fiction","Horror","Humour","Legend","Magical realism","Metafiction","Mystery","Mythology","Mythopoeia","Realistic fiction","Science fiction","Short story","Suspense/Thriller","Tall tale","Western,Biography","Autobiography","Essay","Narrative nonfiction/Personal narrative","Memoir","Speech","Textbook","Reference book","Self-help book","Journalism", "Religon"]

    var ResultArray: [NSObject] = []
    var infoArray:[AnyObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

    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 genreArray.count
}


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

    cell.textLabel?.text = genreArray[indexPath.row]
    return cell
}


override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    typealias CompletionHandler = (result:NSObject?, error: NSError?) -> Void

    func getData(completionHandeler: CompletionHandler){
        let bookRef = self.dataBase.reference().child("books")
        let GenreSelector = self.genreArray[indexPath.row]
        bookRef.queryOrderedByChild("Genre")
            .queryEqualToValue(GenreSelector)
            .observeSingleEventOfType(.Value, withBlock:{ snapshot in
                for child in snapshot.children {
                    print("Loading group \((child.key!))")

                    self.ResultArray.append(child as! NSObject)
                }
                print(self.ResultArray)

                self.performSegueWithIdentifier("letsGo", sender: self)
                self.tableView.reloadData()
            })
    }
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var DestViewController: ResultTableViewController = segue.destinationViewController as! ResultTableViewController
    DestViewController.SecondResultArray = self.ResultArray
}

您可以将数据注入到目标viewController中prepareForSegue第一种方法UIViewController并重新加载你的UITableView in viewDidAppear。如果您异步获取数据,请拥有一个completionHandler 并在completionHandler 中重新加载它。这是一个例子。

  func fetchDataWithCompletion(response: (NSDictionary?, error:NSError?)-> Void) -> Void {
    //make the API call here 
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Segue 传递数据后如何重新加载 tableView 数据 的相关文章

随机推荐