我有一个登录按钮,可进入主页收集视图。加载主页集合视图时程序崩溃。这是主页集合视图的代码。
class CollectionViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating{
var items = [Food]()
var filtered = [Food]()
var searchActive : Bool = false
let searchController = UISearchController(searchResultsController: nil)
// var items = ["ASIAN","SEAFOOD","SUSHI","CAFE","Los Angeles","Austin","Seattle"]
@IBOutlet var collectionViewController: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// imageViewArray=[#imageLiteral(resourceName: "food18") ,#imageLiteral(resourceName: "food19"),#imageLiteral(resourceName: "food20"),#imageLiteral(resourceName: "food21"),#imageLiteral(resourceName: "food22"),#imageLiteral(resourceName: "food23"),#imageLiteral(resourceName: "food24")]
self.items.append(Food(title: "View Appointment", image: UIImage(named: "view [email protected]")))
self.items.append(Food(title: "Medical Chart", image:UIImage(named: "medical [email protected]")))
self.items.append(Food(title: "Task", image:UIImage(named: "[email protected]")))
self.items.append(Food(title: "Referrals", image:UIImage(named: "[email protected]")))
self.items.append(Food(title: "Profile", image:UIImage(named: "[email protected]")))
self.items.append(Food(title: "Wallet", image:UIImage(named: "[email protected]")))
collectionViewController.dataSource=self
collectionViewController.delegate=self
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search for tools and resources"
searchController.searchBar.sizeToFit()
searchController.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchController.searchBar
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchActive {
return filtered.count
}
else
{
return items.count //return number of rows in section
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CategoriesCollectionViewCell
//configureCell(cell: cell as! toolCollectionViewCell, forItemAtIndexPath: indexPath as NSIndexPath)
cell.imageViewCell=cell.viewWithTag(1) as! UIImageView
if searchActive {
cell.imageViewCell.image = self.filtered[indexPath.row].image
cell.categoriesTitleLbl.text = self.filtered[indexPath.row].title
} else {
cell.imageViewCell.image = self.items[indexPath.row].image
cell.categoriesTitleLbl.text = self.items[indexPath.row].title
}
return cell //return your cell
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
self.dismiss(animated: true, completion: nil)
}
func updateSearchResults(for searchController: UISearchController)
{
guard let searchString = searchController.searchBar.text else {
return
}
filtered = items.filter({ (item) -> Bool in
if let title = item.title {
return title.lowercased().contains(searchString.lowercased())
} else {
return false
}
})
collectionViewController.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
collectionViewController.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
collectionViewController.reloadData()
}
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
if !searchActive {
searchActive = true
collectionViewController.reloadData()
}
searchController.searchBar.resignFirstResponder()
}
}
class Food {
var title: String?
var image: UIImage?
init(title: String?, image: UIImage?) {
self.title = title
self.image = image
}
}
这是收集视图单元格的代码
class CategoriesCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageViewCell: UIImageView!
@IBOutlet weak var categoriesTitleLbl: UILabel!
}
如何避免该程序崩溃。并成功加载主页。
您可以从此链接下载项目。 https://drive.google.com/file/d/1HPoFPdTOeKKpMEc_zdLGCGpjmgXe0HRb/view?usp=sharing
错误语句是
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UICollectionViewController 0x7f951651a340> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key collectionViewController.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010a3c212b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000109a56f41 objc_exception_throw + 48
2 CoreFoundation 0x000000010a3c2079 -[NSException raise] + 9
3 Foundation 0x0000000109475a63 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
4 UIKit 0x000000010ac7f117 -[UIViewController setValue:forKey:] + 87
5 UIKit 0x000000010af70c2d -[UIRuntimeOutletConnection connect] + 109
6 CoreFoundation 0x000000010a3653cd -[NSArray makeObjectsPerformSelector:] + 317
7 UIKit 0x000000010af6f5e3 -[UINib instantiateWithOwner:options:] + 1856
8 UIKit 0x000000010ac863ff -[UIViewController _loadViewFromNibNamed:bundle:] + 383
9 UIKit 0x000000010ac86d2b -[UIViewController loadView] + 177
10 UIKit 0x000000010b5f6304 -[UICollectionViewController loadView] + 290
11 UIKit 0x000000010ac8705c -[UIViewController loadViewIfRequired] + 195
12 UIKit 0x000000010ac878b9 -[UIViewController view] + 27
13 UIKit 0x000000010b720441 -[_UIFullscreenPresentationController _setPresentedViewController:] + 89
14 UIKit 0x000000010ac542a3 -[UIPresentationController initWithPresentedViewController:presentingViewController:] + 133
15 UIKit 0x000000010ac9ab67 -[UIViewController _presentViewController:withAnimationController:completion:] + 3808
16 UIKit 0x000000010ac9d9a9 __63-[UIViewController _presentViewController:animated:completion:]_block_invoke + 99
17 UIKit 0x000000010ac9e079 -[UIViewController _performCoordinatedPresentOrDismiss:animated:] + 532
18 UIKit 0x000000010ac9d908 -[UIViewController _presentViewController:animated:completion:] + 181
19 UIKit 0x000000010ac9dc67 -[UIViewController presentViewController:animated:completion:] + 159
20 UIKit 0x000000010aca2fea -[UIViewController _showViewController:withAction:sender:] + 274
21 UIKit 0x000000010b24fe9a __66-[UIStoryboardShowSegueTemplate newDefaultPerformHandlerForSegue:]_block_invoke + 134
22 UIKit 0x000000010b40fc1e -[UIStoryboardSegueTemplate _performWithDestinationViewController:sender:] + 279
23 UIKit 0x000000010b40fad6 -[UIStoryboardSegueTemplate _perform:] + 82
24 UIKit 0x000000010b40fd9e -[UIStoryboardSegueTemplate perform:] + 157
25 UIKit 0x000000010aae0972 -[UIApplication sendAction:to:from:forEvent:] + 83
26 UIKit 0x000000010ac5fc3c -[UIControl sendAction:to:forEvent:] + 67
27 UIKit 0x000000010ac5ff59 -[UIControl _sendActionsForEvents:withEvent:] + 450
28 UIKit 0x000000010ac5ee86 -[UIControl touchesEnded:withEvent:] + 618
29 UIKit 0x000000010ab56807 -[UIWindow _sendTouchesForEvent:] + 2807
30 UIKit 0x000000010ab57f2a -[UIWindow sendEvent:] + 4124
31 UIKit 0x000000010aafb365 -[UIApplication sendEvent:] + 352
32 UIKit 0x000000010b447a1d __dispatchPreprocessedEventFromEventQueue + 2809
33 UIKit 0x000000010b44a672 __handleEventQueueInternal + 5957
34 CoreFoundation 0x000000010a365101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
35 CoreFoundation 0x000000010a404f71 __CFRunLoopDoSource0 + 81
36 CoreFoundation 0x000000010a349a6b __CFRunLoopDoSources0 + 267
37 CoreFoundation 0x000000010a348fff __CFRunLoopRun + 1279
38 CoreFoundation 0x000000010a348889 CFRunLoopRunSpecific + 409
39 GraphicsServices 0x00000001129509c6 GSEventRunModal + 62
40 UIKit 0x000000010aadf5d6 UIApplicationMain + 159
41 WowPatient 0x0000000108f70b47 main + 55
42 libdyld.dylib 0x000000010eb87d81 start + 1
43 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
最佳答案
您的CollectionViewController
中有几个错误
首先,该类是从UIViewController
继承的,但是您的情节提要中有一个UICollectionViewController
,修改CollectionViewController.swift
文件以从UICollectionViewController
继承,如下所示:
class CollectionViewController: UICollectionViewController, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating
在这两种方法的开头添加
override
关键字:func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
编辑您的情节提要,并删除连接检查器中的委托和数据源引用,还删除IBOutlet引用
现在,将
IBOutlet
从情节提要中删除,也将其从类中删除@IBOutlet var collectionViewController:UICollectionView!
现在,如果要访问
UICollectionView
,只需使用self.collectionView
而不是self.collectionViewController
即可,如下所示:self.collectionView?.reloadData()
self.collectionView?.dataSource = self
self.collectionView?.delegate = self
更新,在
class CategoriesCollectionViewCell
中添加override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = .black
}