我正在構建一個具有自定義collectionCell的UICollectionView。但我得到的錯誤:UICollectionView崩潰,因爲佈局參數是「無」..但它不是 - Swift
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'
但你可以從代碼中看到,我很明確地創建佈局和初始化集合視圖時,把它當作一個PARAM。
import UIKit
private let reuseIdentifier = "Cell"
class ProfileViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
sentMngr.retrieveSent()
let flow = UICollectionViewFlowLayout()
flow.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
flow.itemSize = CGSize(width: 90, height: 90)
flow.scrollDirection = UICollectionViewScrollDirection.Vertical
self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: flow)
self.collectionView!.dataSource = self
self.collectionView!.delegate = self
self.collectionView!.backgroundColor = UIColor.blackColor()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(CollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.view.addSubview(self.collectionView!)
// Do any additional setup after loading the view.
}
自定義單元代碼:
import UIKit
class CollectionCell: UICollectionViewCell {
var imageView: UIImageView!
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*2/3))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
您是否嘗試過乾淨重建項目初始化工作得很好? (Cmd + Shift + K) – shpasta
yes no success .. – broderickga
您的視圖控制器繼承自'UICollectionViewController',因此您不需要初始化新的集合視圖並將其分配給'self.collectionView'。嘗試刪除該行並查看會發生什麼。 – AdamPro13