UICollectionView 单元格不显示

UICollectionView Cells Not Showing

我有这段代码,但无法显示单元格。我已经尝试设置背景颜色以查看它们是否出现,只是其中的图像没有出现,但似乎细胞根本没有出现。

编辑:这是完整的代码,还有其他元素的所有内容(大部分内容都被注释掉了)

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.
 }
 */

}

* 注意:通过更改视图控制器的模块修复了错误*

崩溃错误:

2017-05-14 23:27:49.905819 最终项目[25556:734502] [MC] systemgroup.com.apple.configurationprofiles 路径的系统组容器是 /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] 从私人有效用户设置中读取。 2017-05-14 23:27:55.065654 最终项目 [25556:734502] [常见] _BSMachError:端口 7103; (os/kern) 无效能力 (0x14) "Unable to insert COPY_SEND" 2017-05-14 23:27:55.066446 最终项目[25556:734502] [常见] _BSMachError:端口 7103; (os/kern) 无效名称 (0xf) "Unable to deallocate send right" 12345abcde 在 出去 2017-05-14 23:29:01.246 FInal Project[25556:734502] 未知 class Interface Builder 文件中的 AvatarCollectiveCell。 2017-05-14 23:29:01.824 最终项目[25556:734502] * 由于未捕获的异常 'NSUnknownKeyException' 而终止应用程序,原因:'[ setValue:forUndefinedKey:]: 这个class 与键 AvatarImage 的键值编码不兼容。' * 首先抛出调用栈: ( 0 CoreFoundation 0x0000000104948d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x0000000103f8921e objc_exception_throw + 48 2 CoreFoundation 0x0000000104948c99 -[NSException 提升] + 9 3 基金会 0x0000000103a979df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291 4 UIKit 0x0000000105544375 -[UIView(CALayerDelegate) setValue:forKey:] + 173 5 UIKit 0x000000010588e79e -[UIRuntimeOutletConnection 连接] + 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 最终项目 0x00000001039509fb _TFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 171 11 最终项目 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 布局子视图] + 313 16 UIKit 0x0000000105544ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237 17 QuartzCore 0x000000010ae3fbf8 -[CALayer layoutSublayers] + 146 18 石英核 0x000000010ae33440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 石英核 0x000000010ae332be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 20 石英核 0x000000010adc1318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 21 石英核心 0x000000010adee3ff _ZN2CA11Transaction6commitEv + 475 22 UIKit 0x00000001054aa7f0 _afterCACommitHandler + 346 23 核心基础 0x00000001048ed267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 24 核心基础 0x00000001048ed1d7 __CFRunLoopDoObservers + 391 25 核心基础 0x00000001048d1f8e __CFRunLoopRun + 1198 26 核心基础 0x00000001048d1884 CFRunLoopRunSpecific + 420 27 图形服务 0x000000010a64ca6f GSEventRunModal + 161 28 UIKit 0x000000010547fc68 UIApplicationMain + 159 29 最终项目 0x00000001039495bf main + 111 30 libdyld.dylib 0x000000010877268d 开始 + 1 31 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

编辑;

2017-05-15 06:24:55.693709 最终项目[32230:909344] [MC] systemgroup.com.apple.configurationprofiles 路径的系统组容器是 /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 最终项目[32230:909344] [MC] 从私人有效用户设置中读取。 2017-05-15 06:25:01.292524 最终项目[32230:909344] [常见] _BSMachError:端口 7403; (os/kern) 无效能力 (0x14) "Unable to insert COPY_SEND" 2017-05-15 06:25:01.293292 最终项目[32230:909344] [常见] _BSMachError:端口 7403; (os/kern) 无效名称 (0xf) "Unable to deallocate send right" 12345abcde 在 出去 2017-05-15 06:25:11.059 FInal Project[32230:909344] 未知 class Interface Builder 文件中的 AvatarCollectiveCell。 2017-05-15 06:25:11.595 最终项目[32230:909344] * 由于未捕获的异常 'NSUnknownKeyException' 而终止应用程序,原因:'[ setValue:forUndefinedKey:]: 这个class 与键 AvatarImage 的键值编码不兼容。' * 首先抛出调用栈: ( 0 CoreFoundation 0x0000000103c26d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010326721e objc_exception_throw + 48 2 CoreFoundation 0x0000000103c26c99 -[NSException 提升] + 9 3 基金会 0x0000000102d759df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291 4 UIKit 0x0000000104822375 -[UIView(CALayerDelegate) setValue:forKey:] + 173 5 UIKit 0x0000000104b6c79e -[UIRuntimeOutletConnection 连接] + 109 6 核心基础 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 最终项目 0x0000000102c2eafb _TFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 171 11 最终项目 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 石英核 0x000000010a19f440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 石英核 0x000000010a19f2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 20 石英核 0x000000010a12d318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 21 石英核心 0x000000010a15a3ff _ZN2CA11Transaction6commitEv + 475 22 UIKit 0x00000001047887f0 _afterCACommitHandler + 346 23 核心基础 0x0000000103bcb267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 24 核心基础 0x0000000103bcb1d7 __CFRunLoopDoObservers + 391 25 核心基础 0x0000000103baff8e __CFRunLoopRun + 1198 26 核心基础 0x0000000103baf884 CFRunLoopRunSpecific + 420 27 图形服务 0x00000001099b8a6f GSEventRunModal + 161 28 UIKit 0x000000010475dc68 UIApplicationMain + 159 29 最终项目 0x0000000102c276bf main + 111 30 libdyld.dylib 0x0000000107a5068d 开始 + 1 31 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

问题是您根本没有重新加载集合视图。如果您可以在 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() 

尝试在 ViewDidLoad 中添加:

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

您是否设置了集合视图的数据源和委托?您的视图控制器似乎没有实现这些协议。

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

    // ...
}

您也可以通过按住 Ctrl 键从集合视图拖动到视图控制器来从故事板执行此操作。 (您仍然必须在 class 名称/UIViewController 之后声明 UICollectionViewDelegateUICollectionViewDataSource 协议。)

根据完整代码编辑

以下为我编译没有错误,我认为至少是你想要的要点。 (除了与此答案相关的内容外,我没有取消任何评论,即 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.
    }
    */
}

我相信 UICollectionView 委托函数没有调用。向 UICollectionView 委托函数添加断点,

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

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

如果是这种情况,只需添加协议、UICollectionViewDataSource、UICollectionViewDelegate,如下所述。

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

检查那些点

  1. Table 查看约束条件
  2. Delegate 和数据源是否已连接
  3. 检查源数组是否已在某处清理。
  4. 如果仍未出现,则设置 table 视图和 tableviewcell 的背景颜色以测试其外观。 5.仍然没有出现,然后清除派生数据并清理项目,将它们清空垃圾。然后再次 运行。