Swift - 创建集合视图,没有 Storyboard initWithFrame 错误



我正在创建一个没有情节提要的集合视图 - 将其从我的项目中删除。

我在这里,在AppDelegate中创建它。我的页脚和页眉已正确取消排队,加载图像时显示的单元格为零,但我无法弄清楚此方法 initWithFrame 在哪里调用!任何帮助表示赞赏。

不使用情节提要

在应用委托内部调用

let window = UIWindow(frame: UIScreen.main.bounds)
let myTabBar = TabBarVC()
window.rootViewController = myTabBar
window.makeKeyAndVisible()
let homeVC = HomeVC(collectionViewLayout: UICollectionViewFlowLayout())
myTabBar.present(homeVC, animated: false)

这最终会失败,并显示以下错误:

2018-06-26 16:02:15.379473-0700 MMDH[62033:2946934] -[MMDH.HomeVC 
initWithFrame:]: unrecognized selector sent to instance 0x7fdcce82f400
2018-06-26 16:02:15.389976-0700 MMDH[62033:2946934] *** Terminating app due to 
uncaught exception 'NSInvalidArgumentException', reason: '-[MMDH.HomeVC 
initWithFrame:]: unrecognized selector sent to instance 0x7fdcce82f400

我的单元格、页脚、页眉都已取消排队。我无法弄清楚这是错误的哪里...这是设置代码:

class HomeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var headerVC = HeaderView()
var footerVC = homeFooterView()
var photos = [Photo]()
var imageFetchOperationQueue = OperationQueue()
var infoOperationQueue = OperationQueue()
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let cache = NSCache<NSString, UIImage>()
override func viewDidLoad() {
super.viewDidLoad()
layout.itemSize = CGSize(width: (width / 3), height: (width / 3))
layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
layout.headerReferenceSize = CGSize(width: width, height: width / 2)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
if photos.count == 0 {
layout.footerReferenceSize = CGSize(width: width, height: width)
} else if photos.count < 9 {
layout.footerReferenceSize = CGSize(width: 0, height: 0)
} else {
layout.footerReferenceSize = CGSize(width: 0, height: 0)
}
collectionView!.collectionViewLayout = layout
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.register(HomeVC.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "homeVC")
self.view.addSubview(headerVC)
collectionView?.register(homeFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footerVC")
self.view.addSubview(footerVC)
collectionView?.register(HomePicCell.self, forCellWithReuseIdentifier: "Cell")

}
}

您的viewDidLoad方法中存在一些问题。

  1. 您的主要问题是将HomeVC类注册为标头视图类型。你想使用HeaderView.self,而不是HomeVC.self
  2. 不要将布局基于屏幕大小。您的收藏视图可能不会占据整个屏幕。布局基于集合视图的大小。另请注意,大小可能会更改。最好在viewWillTransition方法中更新布局。
  3. 这是一个UICollectionViewController。您不应该创建自己的UICollectionView。在调用viewDidLoad之前,它将为您完成。删除创建集合视图的三行并设置dataSourcedelegate

次要,但您的homeFooterView类应命名为HomeFooterView。类名应以大写字母开头。

最新更新