UICollectionView单元格未显示

时间:2017-05-13 23:34:32

标签: ios swift uicollectionview uicollectionviewcell

我已经获得了这些代码,但我无法让细胞显示出来。我尝试设置背景颜色,看看它们是否出现,只是其中的图像没有出现,但似乎细胞根本没有显示出来。

编辑:这是完整的代码,其他元素也是如此(大多数东西都被注释掉了)

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 FInal Project [25556:734502] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器是/ Users / student / Library / Developer / CoreSimulator / Devices / 265EA47F -07A6-47C7-A6B4-5E62D37E72BA /数据/容器/共享/ SystemGroup / systemgroup.com.apple.configurationprofiles 2017-05-14 23:27:49.990769 FInal Project [25556:734502] [MC]从私人有效用户设置中读取。 2017-05-14 23:27:55.065654 FInal Project [25556:734502] [Common] _BSMachError:port 7103; (os / kern)无效功能(0x14)&#34;无法插入COPY_SEND&#34; 2017-05-14 23:27:55.066446 FInal Project [25556:734502] [Common] _BSMachError:port 7103; (os / kern)无效名称(0xf)&#34;无法解除分配发送权限&#34; 12345abcde 在 退房 2017-05-14 23:29:01.246 FInal Project [25556:734502] Interface Builder文件中的未知类AvatarCollectiveCell。 2017-05-14 23:29:01.824最终项目[25556:734502] *由于未捕获的异常终止应用程序&#39; NSUnknownKeyException&#39;,原因:&#39; [setValue:forUndefinedKey:]:this class不是键值AvatarImage的关键值编码。&#39; * 第一次抛出调用堆栈: (     0 CoreFoundation 0x0000000104948d4b exceptionPreprocess + 171     1 libobjc.A.dylib 0x0000000103f8921e objc_exception_throw + 48     2 CoreFoundation 0x0000000104948c99 - [NSException raise] + 9     3基础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:以NSException类型的未捕获异常终止 (lldb)

编辑;

2017-05-15 06:24:55.693709 FInal Project [32230:909344] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器是/ Users / student / Library / Developer / CoreSimulator / Devices / 265EA47F -07A6-47C7-A6B4-5E62D37E72BA /数据/容器/共享/ SystemGroup / systemgroup.com.apple.configurationprofiles 2017-05-15 06:24:55.694415 FInal Project [32230:909344] [MC]从私人有效用户设置中读取。 2017-05-15 06:25:01.292524最终项目[32230:909344] [通用] _BSMachError:端口7403; (os / kern)无效功能(0x14)&#34;无法插入COPY_SEND&#34; 2017-05-15 06:25:01.293292最终项目[32230:909344] [通用] _BSMachError:端口7403; (os / kern)无效名称(0xf)&#34;无法解除分配发送权限&#34; 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] *由于未捕获的异常终止应用程序&#39; NSUnknownKeyException&#39;,原因:&#39; [setValue:forUndefinedKey:]:this class不是键值AvatarImage的关键值编码。&#39; * 第一次抛出调用堆栈: (     0 CoreFoundation 0x0000000103c26d4b exceptionPreprocess + 171     1 libobjc.A.dylib 0x000000010326721e objc_exception_throw + 48     2 CoreFoundation 0x0000000103c26c99 - [NSException raise] + 9     3基础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:以NSException类型的未捕获异常终止 (lldb)

5 个答案:

答案 0 :(得分:1)

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

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键拖动到视图控制器,从故事板中执行此操作。 (您仍需在类名/ UICollectionViewDelegate后声明UICollectionViewDataSourceUIViewController协议。)

enter image description here enter image description here

根据完整代码进行修改

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

答案 1 :(得分:0)

尝试在ViewDidLoad

中添加此内容
self.collectionView?.register(AvatarCollectiveCell.self, forCellWithReuseIdentifier: reuseIdentifier)

答案 2 :(得分:0)

我相信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}

答案 3 :(得分:0)

检查这些要点

  1. 表视图约束
  2. 代理和数据源已连接或未连接
  3. 检查源阵列是否已在某处清理过。
  4. 如果仍未显示,则设置表格视图和tableviewcell的背景颜色以测试其外观。 5。仍然没有出现然后清除派生数据并清理项目他们emplty垃圾。并再次运行。

答案 4 :(得分:-2)

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