繁体   English   中英

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项目[25556:734502] [MC]从私有有效用户设置中读取。 2017-05-14 23:27:55.065654 FINAL项目[25556:734502] [公用] _BSMachError:端口7103; (os / kern)无效功能(0x14)“无法插入COPY_SEND” 2017-05-14 23:27:55.066446 FINAL Project [25556:734502] [Common] _BSMachError:端口7103; (os / kern)无效名称(0xf)“无法取消分配发送权限” 12345abcde in out 2017-05-14 23:29:01.246 FINAL Project [25556:734502] Interface Builder文件中的未知类AvatarCollectiveCell。 2017-05-14 23:29:01.824 FINAL Project [25556:734502] *由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类不符合该键的键值编码AvatarImage。” *首次调用堆栈:(0 CoreFoundation 0x0000000104948d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x0000000103f8921e objc_exception_throw + 48 2 CoreFoundation 0x0000000104948c99-[NSException提高] + 9 3 Foundation 0x0000000103a979df-[NSObject(NSKeyValueCoding)+] UIKit 0x0000000105544375-[UIView(CALayerDelegate)setValue:forKey:] + 173 5 UIKit 0x000000010588e79e-[UIRuntimeOutletConnection connect] + 109 6 CoreFoundation 0x00000001048ed9e0-[NSArray makeObjectsPerformSelector:] + 256 7 UIKit 0x000000010588di: UIKit 0x0000000105dd2012-[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 1094 9 UIKit 0x0000000105dd28ea-[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169 10 FINALProject 0x00000001039FCACollection16View15ViewCollection_View13CellViewACollection14View1Collection13C 11最终项目0x0000000103950db7 _TToFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87 12的UIKit 0x0000000105dbd75f - [UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:通知:] + 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_trans actionEPNS_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最终项目0x00000001039495bf主+ 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 FINAL项目[32230:909344] [MC]从私有有效用户设置中读取。 2017-05-15 06:25:01.292524 FINAL项目[32230:909344] [公用] _BSMachError:端口7403; (os / kern)无效功能(0x14)“无法插入COPY_SEND” 2017-05-15 06:25:01.293292 FINAL Project [32230:909344] [Common] _BSMachError:端口7403; (os / kern)无效名称(0xf)“无法取消分配发送权限” 12345abcde输入输出2017-05-15 06:25:11.059 FINAL Project [32230:909344] Interface Builder文件中的未知类AvatarCollectiveCell。 2017-05-15 06:25:11.595 FINAL Project [32230:909344] *由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类不适用于密钥编码的键值AvatarImage。” *首先抛出调用堆栈:(0 CoreFoundation 0x0000000103c26d4b exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010326721e objc_exception_throw + 48 2 CoreFoundation 0x0000000103c26c99-[NSException提高] + 9 3 Foundation 0x0000000102d759df-[NSObject(NSKeyValueCoding)+] UIKit 0x0000000104822375-[UIView(CALayerDelegate)setValue:forKey:] + 173 5 UIKit 0x0000000104b6c79e-[UIRuntimeOutletConnection connect] + 109 6 CoreFoundation 0x0000000103bcb9e0-[NSArray makeObjectsPerformSelector:] + 256 7 UIKit 0x0000000b: UIKit 0x00000001050b0012-[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 1094 9 UIKit 0x00000001050b08ea-[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexIndex:] + 169 10 FINAL Project 0x0000000102c2Collection13FC16Collection20FC_Collection16FC 11最终项目0x0000000102c2eeb7 _TToFC13FInal_Project6Avatar14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87 12的UIKit 0x000000010509b75f - [UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:通知:] + 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_trans actionEPNS_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最终项目0x0000000102c276bf main + 111 30 libdyld.dylib 0x0000000107a5068d start + 1 31 ??? 0x0000000000000001 0x0 +1)libc ++ abi.dylib:以类型为NSException(lldb)的未捕获异常终止

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

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键,从集合视图中拖动到视图控制器来执行此操作。 (您仍然必须在类名/ 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.
    }
    */
}

尝试在ViewDidLoad添加它:

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

我相信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. 表格视图约束
  2. 委托和数据源是否已连接
  3. 检查源数组是否已在某处清除。
  4. 如果仍然没有出现,则设置表格视图和表格视图单元格的背景色以测试其外观。 5。 仍然没有出现,然后清除派生数据并清理项目,然后将其清空。然后再次运行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM