xduvall15x
xduvall15x

Reputation: 11

Segue from tableview to view controller

I can't find where I haven't unwrapped my label so I can perform my segue. It keeps saying label doesn't have .text and fatal error: unexpectedly found nil while unwrapping an Optional value

I'm just trying to make the title of my view controller equal to the label text teamNameLabel

    import UIKit

class TimelineTableViewController: UITableViewController {

    var timelineData:NSMutableArray! = NSMutableArray()

    override init(style: UITableViewStyle) {
        super.init(style: style)
        // Custom initialization
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    @IBAction func loadData(){
        timelineData.removeAllObjects()

        var findTimelineData:PFQuery = PFQuery(className: "Sweets")

        findTimelineData.findObjectsInBackgroundWithBlock{
            (objects:[AnyObject]!, error:NSError!)->Void in

            if error == nil{
                for object in objects{
                    let sweet:PFObject = object as PFObject
                    self.timelineData.addObject(sweet)
                }

                let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
                self.timelineData = NSMutableArray(array: array)

                self.tableView.reloadData()

            }

        }
    }

    override func viewDidAppear(animated: Bool) {
        self.loadData()

        if PFUser.currentUser() == nil{
            var loginAlert:UIAlertController = UIAlertController(title: "Sign Up / Login", message: "Please sign up or login", preferredStyle: UIAlertControllerStyle.Alert)

            loginAlert.addTextFieldWithConfigurationHandler({
                    textfield in
                    textfield.placeholder = "Your username"
                })

            loginAlert.addTextFieldWithConfigurationHandler({
                textfield in
                textfield.placeholder = "Your password"
                textfield.secureTextEntry = true
            })

            loginAlert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.Default, handler: {
                    alertAction in
                let textFields:NSArray = loginAlert.textFields! as NSArray
                let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
                let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField

                PFUser.logInWithUsernameInBackground(usernameTextfield.text, password: passwordTextfield.text){
                    (user:PFUser!, error:NSError!)->Void in
                    if user != nil{
                        println("Login successfull")
                    }else{
                        println("Login failed")
                    }


                }




                }))

            loginAlert.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler: {
                alertAction in
                let textFields:NSArray = loginAlert.textFields! as NSArray
                let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
                let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField

                var sweeter:PFUser = PFUser()
                sweeter.username = usernameTextfield.text
                sweeter.password = passwordTextfield.text

                sweeter.signUpInBackgroundWithBlock{
                    (success:Bool!, error:NSError!)->Void in
                    if error == nil{
                        println("Sign Up successfull")
                    }else{
                        let errorString = error.localizedDescription
                        println(errorString)
                    }


                }



                }))

            self.presentViewController(loginAlert, animated: true, completion: nil)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

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

    // #pragma mark - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return timelineData.count
    }


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

        let sweet:PFObject = self.timelineData.objectAtIndex(indexPath!.row) as PFObject

    cell.sweetTextView.alpha = 0
    cell.timestampLabel.alpha = 0
    cell.usernameLabel.alpha = 0
    cell.teamNameLabel.alpha = 0

        cell.sweetTextView.text = sweet.objectForKey("content") as String

        cell.teamNameLabel.text! = sweet.objectForKey("teamName") as String


        var dataFormatter:NSDateFormatter = NSDateFormatter()
        dataFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        cell.timestampLabel.text = dataFormatter.stringFromDate(sweet.createdAt)

        var findSweeter:PFQuery = PFUser.query()
        findSweeter.whereKey("objectId", equalTo: sweet.objectForKey("sweeter").objectId)

        findSweeter.findObjectsInBackgroundWithBlock{
            (objects:[AnyObject]!, error:NSError!)->Void in
            if error == nil{
                let user:PFUser = (objects as NSArray).lastObject as PFUser
                cell.usernameLabel.text = user.username


                UIView.animateWithDuration(0.5, animations: {
                        cell.sweetTextView.alpha = 1
                        cell.timestampLabel.alpha = 1
                        cell.usernameLabel.alpha = 1
                        cell.teamNameLabel.alpha = 1
                    })
            }
        }


        return cell
    }



    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        if segue.identifier == "viewTeam" {

            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let vc = segue.destinationViewController as TeamViewController
                vc.title = timelineData[indexPath.row].teamNameLabel.text
            }

            /*
            if let indexPath = self.tableView.indexPathForSelectedRow() {
            let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController
            controller.title = timelineData[indexPath.row].teamNameLabel
            */

            //viewController.title = TimelineData.teamNameLabel.text
            //}
        }

    }

My problem is in my prepare segue message

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        if segue.identifier == "viewTeam" {

            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let vc = segue.destinationViewController as TeamViewController
                vc.title = timelineData[indexPath.row].teamNameLabel.text
            }

            /*
            if let indexPath = self.tableView.indexPathForSelectedRow() {
            let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController
            controller.title = timelineData[indexPath.row].teamNameLabel
            */

            //viewController.title = TimelineData.teamNameLabel.text
            //}
        }

    }

Here is my cell class

    import UIKit

class SweetTableViewCell: UITableViewCell {

    @IBOutlet var usernameLabel: UILabel! = UILabel()
    @IBOutlet var timestampLabel: UILabel! = UILabel()
    @IBOutlet var teamNameLabel: UILabel! = UILabel()
    @IBOutlet var sweetTextView: UITextView! = UITextView()
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        //teamNameLabel.text = ""
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state

    }

}

This is driving me nuts

Upvotes: 1

Views: 715

Answers (2)

xduvall15x
xduvall15x

Reputation: 11

ok I got it!!! Heres my segue

 // In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if segue.identifier == "viewTeam" {


        if let indexPath = self.tableView.indexPathForSelectedRow() {
            println(timelineData[indexPath.row] .valueForKey("teamName")) //.teamNameLabel?.text)

        (segue.destinationViewController as TeamViewController).title = timelineData[indexPath.row] .valueForKey("teamName")! as? String
        }

        /*

        if let indexPath = self.tableView.indexPathForSelectedRow() {
        let controller = (segue.destinationViewController as TeamViewController).topViewController as TeamViewController
        controller.title = timelineData[indexPath.row].teamNameLabel!.text
        */

        //viewController.title = TimelineData.teamNameLabel.text
        //}
    }

}

Upvotes: 0

mtaylor
mtaylor

Reputation: 1140

I believe the problem is that, in your prepareForSegue method, you are setting the title on the wrong instance of your view controller.

You create the variable vc, and set the title on it, but that does not change the destinationViewController instance.

Try this code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if segue.identifier == "viewTeam" {

        if let indexPath = self.tableView.indexPathForSelectedRow() {
            (segue.destinationViewController as TeamViewController).title = timelineData[indexPath.row].teamNameLabel.text
        }

        /*
        if let indexPath = self.tableView.indexPathForSelectedRow() {
        let controller = (segue.destinationViewController as UINavigationController).topViewController as TeamViewController
        controller.title = timelineData[indexPath.row].teamNameLabel
        */

        //viewController.title = TimelineData.teamNameLabel.text
        //}
    }

}

Upvotes: 0

Related Questions