Ryann786
Ryann786

Reputation: 309

passing values to a Modal UIViewController - Swift

I have a list of user profiles in a UICollectionView and when I tap on one of the users, I have a segue that Modally shows the users profile however I can't seem to pass the values from one View to another. Eg.. Image data, Username, etc.

On my UICollectionViewController I have the following:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showSelectedUserProfile" {

        let cell = sender as! GrafterCell
        let SP = segue.destinationViewController as! SelectedProfileViewController
        let indexPath = self.collectionView?.indexPathForCell(cell)

        var username = allUsernames[indexPath!.row]
        SP.username.text = username

    }
}

cell is the cell from the collection view, SP if the destination view controller

When I run the script I get the following error

fatal error: unexpectedly found nil while unwrapping an Optional value

it shows that SP.username is nil and I don't know why it is nil as it's connected to the Class and called username

class SelectedProfileViewController: UIViewController {

@IBOutlet weak var btnHideSelectedProfileViewController: UIButton!
@IBOutlet weak var userProfilePicture: UIImageView!
@IBOutlet weak var username: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    self.navigationController?.navigationBarHidden = true
}

@IBAction func btnHideSelectedProfileViewControllerClicked(sender: AnyObject) {

    self.dismissViewControllerAnimated(true, completion: nil)

}

}

Upvotes: 0

Views: 850

Answers (1)

Mundi
Mundi

Reputation: 80265

You have an array of objects with a property username with a property text. From that I gather that you are perhaps storing an array of objects where the username property is a UILabel?

This would be very bad design. Your data array should just have data objects, not UI elements. Never use the content of UI elements to store and retrieve data (which is what you seem to be doing). UI elements should be used only to display data.

You need to give your destination controller a property of type String to hold the username information.

Also, don't call a label username which is misleading. If its a label, call it nameLabel to make the code readable and intelligible to an outside reader.

Upvotes: 1

Related Questions