iOS + Firebase - 将数据从 View Controller 发送到详细 View Controller

标签 ios swift firebase

我有一个 ViewController,其中从 RealtimeDatabase 获取数据列表并显示在 UITableView 中。单击帖子时,我希望将 ViewController 中的数据(例如标题、描述和图像)传送到 DetailView 中,即:PostController.Swift进一步调用 RealtimeDatabase 中的更多数据以显示在 PostController.Swift

我尝试使用 didSelectRowAt 但无法在 PostController 中获取和显示数据,我目前也在尝试使用 prepare 但卡在同一个地方。

这是 ViewController.Swift:

import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView = UITableView(frame: view.bounds, style: .plain)
        view.addSubview(tableView)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        var layoutGuide:UILayoutGuide!

        layoutGuide = view.safeAreaLayoutGuide

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.reloadData()

        observePosts()

    }

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

    func observePosts() {
        let postsRef = Database.database().reference().child("Data")

        postsRef.observe(.value, with: { snapshot in
            var tempPosts = [Post]()

            for child in snapshot.children{

                if let childSnapshot = child as? DataSnapshot,
                    let dict = childSnapshot.value as? [String:Any],
                    let title = dict["title"] as? String,
                    let logoImage = dict["image"] as? String,
                    let url = URL(string:logoImage),
                    let description = dict["description"] as? String{


                    let userProfile = UserProfile(title: title, photoURL: url)
                    let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
                    print(post)
                    tempPosts.append(post)
                }
            }

            self.posts = tempPosts
            self.tableView.reloadData()
        })
    }

    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!)) 
            } else {
                completion(nil)
            }
            }.resume()
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        tableView.estimatedRowHeight = 50
        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "PostDetailSegue" {


            if let indexPaths = self.tableView!.indexPathForSelectedRow{

            }

        }
    }
}

最佳答案

您需要在 DetailViewController 中存储对 Post 的引用。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "PostDetailSegue" {
        let detailViewController = segue.destinationViewController as! DetailViewController
        let indexPath = tableView.indexPathForSelectedRow
        let post = posts[indexPath.row]
        detailViewController.setPost(post)

    }
}

在你的 DetailViewController 中:

func detailViewController.setPost(_ post: Post) {
    // Store the post and fetch other data as necessary
    self.post = post
}

关于iOS + Firebase - 将数据从 View Controller 发送到详细 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53152747/

相关文章:

ios - 更改其他 Swift 标志会导致构建错误

ios - 像素缓冲区不会附加到设备上的 AVAssetWriterInput

ios - 在编辑表格 View 单元格时获取滑动事件

javascript - storageRef.child 不是 firebase 中的函数

iphone - NSDictionary 没有正确存储 CGRect?

ios - 使用简洁形式的 NSManagedObjectID URI?

javascript - 我无法将数据从 firebase 显示到我的 Node js 客户端

java - 如何从firebase数据库获取所有子节点?

html - iOS:在 HTML NSString 中查找特定段落的结尾

ios - 使用 DatePicker 和 TextField 时将 String 转换为 NSDate