samedi 27 juin 2015

How to load an array based on selected cell value from previous controller in Swift

I'm trying to build something close to the way the note app works but when you select the note instead of text you have a collectionView with cells loaded from an array.

Say I have two viewControllers connected to each other. The firstViewController has a collectionView loaded with the note names and upon selecting a note it will segue to the secondViewController that will load the array for that note.

I have a hard time understanding the logic... Do I work with NSUserDefaults and create an objectForKey for every note or do I create a new array for every note. How would I store these?

firstViewController

class MainViewController: UIViewController, UICollectionViewDelegate {

 var objects = Array<NSDate>()


 @IBAction func insertNewObject(sender: AnyObject) {

    objects.insert(NSDate(), atIndex: 0)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
}

 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

storyboard?.instantiateViewControllerWithIdentifier("secondtView") as! SecondViewController

//How do I proceed here? 

}
}

secondViewController

var myArray:[[AnyObject]] = []
class SecondViewController: UIViewController, UICollectionViewDelegate {


override func viewDidLoad() {
    super.viewDidLoad()
    if (NSUserDefaults.standardUserDefaults().objectForKey("myArray") != nil) {
    myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as! [[AnyObject]]
    }
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      myArray.count
}



 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> CollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell 
 cell.cellLabel.text = myArray[indexPath.row][0] as? String
 return cell 
}

Aucun commentaire:

Enregistrer un commentaire