简体   繁体   English

快速将TableView单元中的数据传递给视图控制器

[英]Swift Passing Data in a tableview cell to a view controller

I seem to be running into an issue and don't know where I am going wrong. 我似乎遇到了一个问题,不知道我要去哪里错了。 I am trying to send the user's post to another view controller through a button, and my app keeps crashing. 我试图通过一个按钮将用户的帖子发送到另一个视图控制器,但我的应用不断崩溃。 Below is the code for the tableview cell and the the prepare for segue. 下面是表格视图单元格和代码准备的代码。 I am still new to the app development world. 我对应用程序开发领域还是陌生的。 So I am sorry if my code is a little messy. 因此,对不起,我的代码有些混乱。 Also I am using Parse as my backend. 另外,我正在使用Parse作为后端。 I don't know if that makes a difference. 我不知道这有什么不同。

thank you in advanced! 在此先感谢您!

    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)
        }
    }

You can change performSegueWithIdentifier("reportPost", sender: self) to performSegueWithIdentifier("reportPost", sender: indexPath) Then, in prepareForSegue() , the sender is going to be the indexPath. 您可以将performSegueWithIdentifier("reportPost", sender: self)更改为performSegueWithIdentifier("reportPost", sender: indexPath)然后,在prepareForSegue()sender将成为indexPath。 You can change your prepareForSegue() to this: 您可以将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)
    }
}

If you do it this way, you can get rid of var valueToPass: String! 如果这样做,可以摆脱var valueToPass: String! above tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 以上tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从 tableview 单元格传递到 View Controller Swift 2.1 - Passing data from tableview cell to View Controller Swift 2.1 将字符串从TableView单元格传递到Swift 3中的View Controller - Passing a string from a TableView cell into a View Controller in Swift 3 数据将tableview单元格传递到Swift中的标签栏视图控制器 - Data pass tableview cell to tab bar view controller in Swift ios Swift:将数据从tableView传递到视图控制器 - ios Swift: Passing data from tableView to view controller 如何在swift 4中正确地在tableview控制器单元内的tableview中重新加载数据? - how to reload data in tableview inside tableview controller cell correctly in swift 4? Swift,如何将 tableview 数据传递给视图控制器? - Swift, how to pass tableview data to view controller? 如何将选定的tableview单元格文本发送到iOS中的前一个视图控制器,Objective C(向后传递数据) - How to send selected tableview cell text to previous view controller in iOS, Objective C (passing data backward) Swift:当用户点击Tableview单元格时,如何将数据从一个视图控制器转移到另一个 - Swift: How to SHIFT data from one view controller to another when the user taps on the Tableview Cell 无法在两个 TableView 视图控制器 Swift4 中使带有标识符的单元格出列 - unable to dequeue a cell with identifier in a two TableView View Controller Swift4 将数据从集合视图单元格按钮传递到另一个视图控制器(Swift) - Passing data from a collection view cell button to another view controller (Swift)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM