Swift将tableview单元格中的数据传递给视图控制器

时间:2015-07-06 18:38:22

标签: ios swift uitableview parsing

我似乎遇到了一个问题而且不知道我哪里出错了。我试图通过按钮将用户的帖子发送到另一个视图控制器,我的应用程序不断崩溃。下面是tableview单元格的代码和segue的准备。我还是应用程序开发世界的新手。所以如果我的代码有点乱,我很抱歉。我也使用Parse作为我的后端。我不知道这是否有所作为。

先谢谢你!

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

        let userPost: PFObject = self.userObjects.objectAtIndex(indexPath.row) as! PFObject

        cell.backgroundColor = UIColor.darkGrayColor().colorWithAlphaComponent(0.2)
        cell.layer.borderColor = UIColor.lightGrayColor().CGColor
        cell.layer.borderWidth = 0.5
        cell.reportPost.tag = indexPath.row
        cell.reportPost.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)

//        Display Users Post's
        var userText = userPost["text"] as? String
        cell.TextLabel!.text = userText

//      Display Date and Time

        var Date: NSDateFormatter = NSDateFormatter()
        Date.dateFormat = "MM-dd HH:mm"
        cell.dateLabel.text = Date.stringFromDate(userPost.createdAt!)

//      Display username

        var findUser:PFQuery = PFUser.query()!
        let Id = userPost.objectForKey("username")?.objectId as NSString!
        findUser.whereKey("objectId", equalTo: Id)
        findUser.findObjectsInBackgroundWithBlock{
            (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil{
                var user:PFUser = (objects as NSArray!).lastObject as! PFUser

                cell.userLabel.text = user.username

//              Getting User's Profile Image

                var initialThumbnail = UIImage(named: "PAHS_Logo")
                cell.userImage.image = initialThumbnail

                if let PhotoFile = user["ProfileImage"] as? PFFile {
                    PhotoFile.getDataInBackgroundWithBlock{
                        (ImageData:NSData?, error:NSError?)->Void in
                        if error == nil{
                            let Image:UIImage = UIImage(data: ImageData!)!
                            cell.userImage.image = Image
                        }else{
                            cell.userImage.image = initialThumbnail
                        }
                    }
                }
            }
        }

        return cell
    }


    func buttonAction(sender: UIButton!){
        let titleString = self.userObjects.objectAtIndex(sender.tag) as? String
        let firstActivityItem = "\(titleString)"
        let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)
        self.presentViewController(activityViewController, animated: true, completion: nil)
    }

    var valueToPass: String!

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let indexPath = tableView.indexPathForSelectedRow();
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
        valueToPass = currentCell.textLabel?.text
        performSegueWithIdentifier("reportPost", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "reportPost")
        {
            var viewController: reportViewController = segue.destinationViewController as! reportViewController
            let indexPath = self.tableView!.indexPathsForSelectedRows();
            let titleString = userObjects.objectAtIndex(indexPath!.count) as! String
            viewController.titleString = titleString
            viewController.titleLabel.text = valueToPass  //fatal error: unexpectedly found nil while unwrapping an Optional value
            self.presentViewController(viewController, animated: true, completion: nil)
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以将performSegueWithIdentifier("reportPost", sender: self)更改为performSegueWithIdentifier("reportPost", sender: indexPath)然后,在prepareForSegue()中,sender将成为indexPath。您可以将prepareForSegue()更改为此:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if (segue.identifier == "reportPost")
   {
        var viewController: reportViewController = segue.destinationViewController as! reportViewController
        let indexPath = sender as! NSIndexPath
        let titleString = userObjects[indexPath.row] as! String // I am assuming userObjects is the object containing the data you want
        viewController.titleString = titleString
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! UITableViewCell
        let valueToPass = cell.textLabel?.text
        viewController.titleLabel.text = valueToPass
        self.presentViewController(viewController, animated: true, completion: nil)
    }
}

如果你这样做,你可以摆脱var valueToPass: String!以上的tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)