认为没有在Swift中发送正确的单元格信息

时间:2015-11-02 02:46:35

标签: swift uitableview parse-platform swift2

我有一个tableView,当按下一个单元格时会触发一个细节视图。该表包含currentUser与之友好的用户列表。按下单元格会加载该用户的视图(名称,配置文件等)。这是一个非常简单的应用程序,我正在创建以学习如何编程。

问题在于,当我按下一个单元格时,它总是加载表格中最后一个用户的用户信息(也恰好是用户制作的最新“朋友”)。我感觉问题出在tableView函数中的if语句:

extension MatchesViewController: UITableViewDataSource
{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return numberOfMatches
    }

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

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

        if PFUser.currentUser()!.objectId == self.user1.objectId{
            let user = matchesResults[indexPath.row]["user2"] as! PFUser
            cell.textLabel?.text = user["first_name"] as! String
            self.viewUser = user
        }

        if PFUser.currentUser()!.objectId == self.user2.objectId{
            let user = matchesResults[indexPath.row]["user1"] as! PFUser
            cell.textLabel?.text = user["first_name"] as! String
            self.viewUser = user
        }

        return cell
    }

    }

这是segue代码,但我认为它没有问题(尽管我可能错了):

extension MatchesViewController: UITableViewDelegate
{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {   
        self.performSegueWithIdentifier("UserSegue", sender: "viewUser")
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "UserSegue") {
            let destinationVC = segue.destinationViewController as! UserViewController
            destinationVC.user = self.viewUser
        }
    }

    }

有什么想法吗?如果我的tableView If语句出现问题,我该如何解决?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过user获取indexPath对象,而不是通过sender方法的performSegueWithIdentifier参数传递

extension MatchesViewController: UITableViewDelegate
{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {   
       let user:PFUser?
       if PFUser.currentUser()!.objectId == self.user1.objectId{
           user = matchesResults[indexPath.row]["user2"] as! PFUser
       }

        if PFUser.currentUser()!.objectId == self.user2.objectId{
           user = matchesResults[indexPath.row]["user1"] as! PFUser
       }
       self.performSegueWithIdentifier("UserSegue", sender: user)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
       // sender is the user object
        if (segue.identifier == "UserSegue") {
            let destinationVC = segue.destinationViewController as! UserViewController
            destinationVC.user = sender  // maybe you need cast sender to UserObject
        }
    }

}