2
votes

I've got this bit of code, and I can't get the cells to show up. I've tried setting a background colour to see if they were showing up and it was just the images within them that weren't appearing, but it seems that the cells aren't showing up at all.

Edit: This is the full code, with everything from other elements as well (Most things are commented out)

import UIKit
import CoreData

//Things in the collection cell
class AvatarCollectiveCell: UICollectionViewCell {
@IBOutlet weak var AvatarImage: UIImageView!

}

class Avatar: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

// Collection View Within View Controller
@IBOutlet weak var CollectionView: UICollectionView!

// Avatar Images

var AvatarImages = ["Avacado", "Bear", "Cow", "Carrot", "Dolphin", "Dinosaur", "Elephant", "Flamingo", "Fox", "Hippo", "Jellyfish", "Moose", "Monkey", "Octopus", "Pig", "Panda", "Parrot", "Pumpkin", "Popcorn", "Penguin", "Platypus", "Sheep", "Sloth", "Shark", "Wolf"]
//AvatarCollectionView.reloaddata()
//
// CollectionView.dataSource = self
//CollectionView.delegate = self
//UICollectionView.reloadData()
// CollectionView.reloadData()

// Create Cells
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return AvatarImages.count //Number of Images
}


// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AvatarCell", for: indexPath as IndexPath) as! AvatarCollectiveCell
    let Avatars = AvatarImages[indexPath.item]




    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    //cell.BookCover.image = UIImage(named: arrayBookImages[indexPath.item])
    cell.AvatarImage.image = UIImage(named: AvatarImages[indexPath.item-1])
    cell.backgroundColor = UIColor.white // make cell more visible in our example project

    return cell
}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // USERNAME DISPLAY BEGINS
    /*
     //reload the data for the collection view
     //NameDisplay.reloadData()

     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
     return
     }

     //getting the managed context where the entity we need is
     let managedContext = appDelegate.persistentContainer.viewContext

     //make fetch request
     let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "UserInfo", attributeName: "name")


     //try to fetch the entity we need, else print error
     do {
     Username = try managedContext.fetch(fetchRequest)
     } catch let error as NSError {
     print("Could not fetch. \(error), \(error.userInfo)")
     }*/
    //USERNAME DISPLAY ENDS


}


override func viewDidLoad() {
    //  CollectionView.dataSource = self
    //   CollectionView.delegate = self
    //super.viewDidLoad()
    // Avatar.collectionView?.register(AvatarCollectiveCell.self, forCellWithReuseIdentifier: ObjectIdentifier)

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

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

var Username:String = ""
@IBOutlet weak var NameDisplay: UILabel!
/*
 // MARK: - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 // Get the new view controller using segue.destinationViewController.
 // Pass the selected object to the new view controller.
 }
 */

}

* Note: Errors were fixed by changing the module of the view controller*

Error it crashes with:

2017-05-14 23:27:49.905819 FInal Project[25556:734502] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/student/Library/Developer/CoreSimulator/Devices/265EA47F-07A6-47C7-A6B4-5E62D37E72BA/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2017-05-14 23:27:49.990769 FInal Project[25556:734502] [MC] Reading from private effective user settings. 2017-05-14 23:27:55.065654 FInal Project[25556:734502] [Common] _BSMachError: port 7103; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" 2017-05-14 23:27:55.066446 FInal Project[25556:734502] [Common] _BSMachError: port 7103; (os/kern) invalid name (0xf) "Unable to deallocate send right" 12345abcde in Out 2017-05-14 23:29:01.246 FInal Project[25556:734502] Unknown class AvatarCollectiveCell in Interface Builder file. 2017-05-14 23:29:01.824 FInal Project[25556:734502] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key AvatarImage.' * First throw call stack: ( 0 CoreFoundation 0x0000000104948d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x0000000103f8921e objc_exception_throw + 48 2 CoreFoundation 0x0000000104948c99 -[NSException raise] + 9 3 Foundation 0x0000000103a979df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291 4 UIKit 0x0000000105544375 -[UIView(CALayerDelegate) setValue:forKey:] + 173 5 UIKit 0x000000010588e79e -[UIRuntimeOutletConnection connect] + 109 6 CoreFoundation 0x00000001048ed9e0 -[NSArray makeObjectsPerformSelector:] + 256 7 UIKit 0x000000010588d122 -[UINib instantiateWithOwner:options:] + 1867 8 UIKit 0x0000000105dd2012 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 1094 9 UIKit 0x0000000105dd28ea -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169 10 FInal Project 0x00000001039509fb _TFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 171 11 FInal Project 0x0000000103950db7 _TToFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87 12 UIKit 0x0000000105dbd75f -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 467 13 UIKit 0x0000000105dbd586 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 35 14 UIKit 0x0000000105dc2a5e -[UICollectionView _updateVisibleCellsNow:] + 4803 15 UIKit 0x0000000105dc8725 -[UICollectionView layoutSubviews] + 313 16 UIKit 0x0000000105544ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237 17 QuartzCore 0x000000010ae3fbf8 -[CALayer layoutSublayers] + 146 18 QuartzCore 0x000000010ae33440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 QuartzCore 0x000000010ae332be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 20 QuartzCore 0x000000010adc1318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 21 QuartzCore 0x000000010adee3ff _ZN2CA11Transaction6commitEv + 475 22 UIKit 0x00000001054aa7f0 _afterCACommitHandler + 346 23 CoreFoundation 0x00000001048ed267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 24 CoreFoundation 0x00000001048ed1d7 __CFRunLoopDoObservers + 391 25 CoreFoundation 0x00000001048d1f8e __CFRunLoopRun + 1198 26 CoreFoundation 0x00000001048d1884 CFRunLoopRunSpecific + 420 27 GraphicsServices 0x000000010a64ca6f GSEventRunModal + 161 28 UIKit 0x000000010547fc68 UIApplicationMain + 159 29 FInal Project 0x00000001039495bf main + 111 30 libdyld.dylib 0x000000010877268d start + 1 31 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Edits;

2017-05-15 06:24:55.693709 FInal Project[32230:909344] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/student/Library/Developer/CoreSimulator/Devices/265EA47F-07A6-47C7-A6B4-5E62D37E72BA/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2017-05-15 06:24:55.694415 FInal Project[32230:909344] [MC] Reading from private effective user settings. 2017-05-15 06:25:01.292524 FInal Project[32230:909344] [Common] _BSMachError: port 7403; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" 2017-05-15 06:25:01.293292 FInal Project[32230:909344] [Common] _BSMachError: port 7403; (os/kern) invalid name (0xf) "Unable to deallocate send right" 12345abcde in Out 2017-05-15 06:25:11.059 FInal Project[32230:909344] Unknown class AvatarCollectiveCell in Interface Builder file. 2017-05-15 06:25:11.595 FInal Project[32230:909344] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key AvatarImage.' * First throw call stack: ( 0 CoreFoundation 0x0000000103c26d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010326721e objc_exception_throw + 48 2 CoreFoundation 0x0000000103c26c99 -[NSException raise] + 9 3 Foundation 0x0000000102d759df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291 4 UIKit 0x0000000104822375 -[UIView(CALayerDelegate) setValue:forKey:] + 173 5 UIKit 0x0000000104b6c79e -[UIRuntimeOutletConnection connect] + 109 6 CoreFoundation 0x0000000103bcb9e0 -[NSArray makeObjectsPerformSelector:] + 256 7 UIKit 0x0000000104b6b122 -[UINib instantiateWithOwner:options:] + 1867 8 UIKit 0x00000001050b0012 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 1094 9 UIKit 0x00000001050b08ea -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169 10 FInal Project 0x0000000102c2eafb _TFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 171 11 FInal Project 0x0000000102c2eeb7 _TToFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87 12 UIKit 0x000000010509b75f -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 467 13 UIKit 0x000000010509b586 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 35 14 UIKit 0x00000001050a0a5e -[UICollectionView _updateVisibleCellsNow:] + 4803 15 UIKit 0x00000001050a6725 -[UICollectionView layoutSubviews] + 313 16 UIKit 0x0000000104822ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237 17 QuartzCore 0x000000010a1abbf8 -[CALayer layoutSublayers] + 146 18 QuartzCore 0x000000010a19f440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 QuartzCore 0x000000010a19f2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 20 QuartzCore 0x000000010a12d318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 21 QuartzCore 0x000000010a15a3ff _ZN2CA11Transaction6commitEv + 475 22 UIKit 0x00000001047887f0 _afterCACommitHandler + 346 23 CoreFoundation 0x0000000103bcb267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 24 CoreFoundation 0x0000000103bcb1d7 __CFRunLoopDoObservers + 391 25 CoreFoundation 0x0000000103baff8e __CFRunLoopRun + 1198 26 CoreFoundation 0x0000000103baf884 CFRunLoopRunSpecific + 420 27 GraphicsServices 0x00000001099b8a6f GSEventRunModal + 161 28 UIKit 0x000000010475dc68 UIApplicationMain + 159 29 FInal Project 0x0000000102c276bf main + 111 30 libdyld.dylib 0x0000000107a5068d start + 1 31 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

5
check this answer for the solution stackoverflow.com/questions/3088059/…Maddy
select your view controller and remove the objects that have no outletsMaddy
Thank you! It's now crashing with the error added to the original postR. R
AvatarImage has a wrong outlet check on your controllerMaddy
The only outlet it has is one to the collective cell, and if I remove it, I get errors within the codeR. R

5 Answers

3
votes

Did you set the collection view's datasource and delegate? Your view controller doesn't seem to implement those protocols.

class Avatar: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    // Collection View Within View Controller
    @IBOutlet weak var CollectionView: UICollectionView!

    // Avatar Images

    var AvatarImages = ["Avacado", "Bear", "Cow", "Carrot", "Dolphin", "Dinosaur", "Elephant", "Flamingo", "Fox", "Hippo", "Jellyfish", "Moose", "Monkey", "Octopus", "Pig", "Panda", "Parrot", "Pumpkin", "Popcorn", "Penguin", "Platypus", "Sheep", "Sloth", "Shark", "Wolf"]

    override func viewDidLoad() {
       CollectionView.dataSource = self
       CollectionView.delegate = self
       // other setup stuff if you need it...
    }

    // ...
}

You can also do this from the storyboard by Ctrl-dragging from the collection view to the view controller. (You still have to declare the UICollectionViewDelegate and UICollectionViewDataSource protocols after your class name/UIViewController.)

enter image description here enter image description here

Edit based on full code

The following compiles for me with no errors, and I think is at least the gist of what you want. (I did not uncomment anything except what was relevant to this answer, i.e. anything outside of viewDidLoad.)

import UIKit
import CoreData

//Things in the collection cell
class AvatarCollectiveCell: UICollectionViewCell {
    @IBOutlet weak var AvatarImage: UIImageView!
}

class Avatar: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {


    // Collection View Within View Controller
    @IBOutlet weak var CollectionView: UICollectionView!

    // Avatar Images

    var AvatarImages = ["Avacado", "Bear", "Cow", "Carrot", "Dolphin", "Dinosaur", "Elephant", "Flamingo", "Fox", "Hippo", "Jellyfish", "Moose", "Monkey", "Octopus", "Pig", "Panda", "Parrot", "Pumpkin", "Popcorn", "Penguin", "Platypus", "Sheep", "Sloth", "Shark", "Wolf"]

    // Create Cells
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return AvatarImages.count //Number of Images
    }


    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AvatarCell", for: indexPath as IndexPath) as! AvatarCollectiveCell
        let Avatars = AvatarImages[indexPath.item]




        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        //cell.BookCover.image = UIImage(named: arrayBookImages[indexPath.item])
        cell.AvatarImage.image = UIImage(named: AvatarImages[indexPath.item-1])
        cell.backgroundColor = UIColor.white // make cell more visible in our example project

        return cell
    }


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // USERNAME DISPLAY BEGINS
        /*
        //reload the data for the collection view
        //NameDisplay.reloadData()

         guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
             return
         }

         //getting the managed context where the entity we need is
         let managedContext = appDelegate.persistentContainer.viewContext

         //make fetch request
         let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "UserInfo", attributeName: "name")


         //try to fetch the entity we need, else print error
         do {
             Username = try managedContext.fetch(fetchRequest)
         } catch let error as NSError {
             print("Could not fetch. \(error), \(error.userInfo)")
         }*/
        //USERNAME DISPLAY ENDS


    }


    override func viewDidLoad() {
        super.viewDidLoad()
        CollectionView.dataSource = self
        CollectionView.delegate = self

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

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

    var Username:String = ""
    @IBOutlet weak var NameDisplay: UILabel!
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
}
0
votes

Try adding this in ViewDidLoad:

self.collectionView?.register(AvatarCollectiveCell.self, forCellWithReuseIdentifier: reuseIdentifier)
0
votes

I believe that UICollectionView delegates functions are not calling. Add a breakpoint to UICollectionView delegate functions that are,

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 

and

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

If that's the case just add protocols, UICollectionViewDataSource, UICollectionViewDelegate as mentioned below.

class Avatar: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate{ // Your code here}
-1
votes

Check those points

  1. Table view constraints
  2. Delegate and datasource has been connected or not
  3. Check if source array has been cleaned somewhere .
  4. If still not appearing then set background color of table view and tableviewcell to test thir appearence. 5 . still not appearing then clear derived data and clean the project them emplty trash .and run again.
-2
votes

The problem is that you are not reloading the collection view at all. If you could add the following in ViewDidLoad()

var AvatarImages = ["Avacado", "Bear", "Cow", "Carrot", "Dolphin", "Dinosaur", "Elephant", "Flamingo", "Fox", "Hippo", "Jellyfish", "Moose", "Monkey", "Octopus", "Pig", "Panda", "Parrot", "Pumpkin", "Popcorn", "Penguin", "Platypus", "Sheep", "Sloth", "Shark", "Wolf"]

UICollectionView.reloadData()