【问题标题】:how to pass dictionary with key to table view如何将带有键的字典传递给表视图
【发布时间】:2016-08-22 14:31:22
【问题描述】:
    import UIKit
import Firebase

class PendingVC: UIViewController,UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var myTableView: UITableView!

let ref = firebasehelper.firebaseURL()
var data = [[:]]




//MARK: vars
        var address:AnyObject!
        var postTitle:AnyObject!
    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.dataSource = self
        myTableView.delegate = self

//下面的例子很好用,我得到了它应该看起来的布局,但我想从下面的 firebase 函数生成字典。

/*
     self.data = [
     [
     "firstname": "sallie",
     "lastname": "ammy"
     ],
     [
     "firstname": "jamie",
     "lastname": "brown"
     ]
     ]

     */

它应该看起来像这样,我想将数据传递到表格中。我不确定我是否应该循环播放。下面的方式会带来以下错误“致命错误:在展开可选值时意外发现 nil”当我打印它们时变量不是 nil,我会取回数据。

ref.childByAppendingPath("backend/posts").queryOrderedByChild("requestFrom").queryEqualToValue(ref.authData.uid).observeEventType(.ChildAdded, withBlock: {snapshot in
                var firstname = snapshot.value["firstname"] as! String
                var lastname = snapshot.value["lastname"] as! String


         self.data = [
            [
                "firstname": firstname,
                "lastname": lastname
            ]
        ]



       print(self.data)
    })







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

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


    let object = data[indexPath.row]



cell.firstname.text = object["firstname"] as! String
  cell.lastname.text = object["lastname"] as! String


    return cell
}


override func viewWillAppear(animated: Bool) {
    navigationController?.navigationBarHidden = false

    navigationController?.navigationBar.barTintColor = UIColor(red:0.4, green:0.76, blue:0.93, alpha:1.0)
    navigationController?.navigationBar.translucent = false
    self.title = "Signup"

    self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
}
}

【问题讨论】:

  • [:] 是字典而不是数组

标签: ios swift firebase


【解决方案1】:

虽然您可以将字典用作数据源,但它是无序的,这意味着您的 tableView 中的项目也将是无序的。使用数组是更好的解决方案。事实上,字典数组是一个很好的有序数据源。

另外,澄清一下,您不会根据您的问题将字典或数据传递给 tableView。 tableView 通过它的委托方法从数据源收集它的数据

假设以下 Firebase 数据结构

"users" : {
    "uid_0" : {
      "first_name" : "Bill",
      "last_name" : "Nye"
    },
    "uid_1" : {
      "first_name" : "Leroy",
      "last_name" : "Jenkins"
    },
    "uid_2" : {
      "first_name" : "Peter",
      "last_name" : "Sellers"
    }
  }

并填充字典数组:

var usersArray: [Dictionary<String, String>] = []

let usersRef = self.myRootRef.childByAppendingPath("users")

usersRef.observeEventType(.ChildAdded, withBlock: { snapshot in

  var userDict = [String:String]()
  userDict["key"] = snapshot.key
  userDict["firstName"] = snapshot.value["first_name"] as? String
  userDict["lastName"] = snapshot.value["last_name"] as? String         
  self.usersArray.append(userDict)
})

要访问数据,请使用您在上面创建的密钥。

例如:从按钮打印数组中的用户

for userDict in self.usersArray {
    let key = userDict["key"]
    let fName = userDict["firstName"]
    let lName = userDict["lastName"]

    print("\(key!)  \(fName!)  \(lName!)")
}

一旦你理解了这一点,你就可以使用 usersArray 来填充 tableView。

let userDict = usersArray[indexPath.row]
cell.firstname.text = userDict["firstName"] as! String
cell.lastname.text = userDict["lastName"] as! String

棘手的一点是在数组中加载所需的所有数据,然后重新加载 tableView 以显示它。如果您有一小部分数据,.Value 将适用。更大的数据集需要另一种技术,请参阅This Answer

【讨论】:

  • 我意识到的一件事是 .ChildAdded 不断返回项目为零。一旦我将其更改为 .Value,我就能够从 Firebase 获取数据。在 cellForRowAtIndexPath 函数中,我在“let userDict = usersArray[indexPath.row]”处收到“致命错误:索引超出范围”
  • @peter 那是因为当您使用 .Value 时,它​​会返回该节点中的所有内容;所有子节点,它们的子节点等。使用 .Value,您需要使用 for child in snapshot.children 遍历子节点,然后从每个 child构建您的字典> 在那个循环中。循环结束后,调用tableView.reloadData
  • 一切都很好,直到我尝试将 UserDict 放在 firebase 闭包之外的 tableview cellForRowAtIndexPath 函数中。在使用之前,我尝试在 firebase 函数之外声明该变量,但没有运气。我也尝试在函数中使用 firebase 函数,但它再次位于闭包中,因此无法正常工作。我一直在努力解决这个问题,但没有运气。
  • @peter 为什么要将 UserDict 放在 firebase 闭包之外?您的 ARRAY 是保存 tableView 数据的东西。该数组是一系列字典。数组在闭包外由这一行 var usersArray: [Dictionary] = [] 定义,并在闭包内填充字典。该数组将“徘徊”并且可以在类中的其他任何地方访问(或函数取决于您放置它的位置)
【解决方案2】:

您正在使用字典,因此它不会返回计数值,因此最好使用 [] 之类的数组而不是 [:]

还有一件事您忘记了要包含在 ViewDidLoad 方法中的以下语句 myTableView.delegate = 自我

【讨论】:

  • @ramaKrisma 我能够将字典放到表格中,我现在遇到的问题是生成数据我得到一个零答案我不知道为什么请看一下问题编辑。跨度>
猜你喜欢
  • 2012-09-15
  • 2021-12-06
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多