即使设置了布局参数,也会出现'UICollectionView must be initialized with a non-nil layout parameter'问题



您可以从下面的代码中看到布局参数已在ViewDidLoad()中设置,但它给了我一个错误:

由于未捕获的异常而终止应用 'NSInvalidArgumentException', reason: 'UICollectionView Must are 使用非 nil 布局参数初始化'

var layer: UICollectionViewFlowLayout = {
var item = UICollectionViewFlowLayout()
item.itemSize = CGSize(width: 100, height: 100)
return item
}()

UICollectionView对象已在属性初始值设定项中设置,因为显然我希望全局可访问此UICollectionView对象:

var dataCollectionViews = UICollectionView()
viewDidLoad(){
dataCollectionViews = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0) , collectionViewLayout: self.layer)
view.addSubview(dataCollectionViews)
self.dataCollectionViews.delegate = self
self.dataCollectionViews.dataSource = self
self.dataCollectionViews.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewReuse)
self.dataCollectionViews.layer.cornerRadius = 10
self.dataCollectionViews.translatesAutoresizingMaskIntoConstraints = false
self.dataCollectionViews.isHidden = true
changed()
}

当我将changed()内的内容移动到viewDidLoad()内部并在viewDidLoad()内部初始化dataCollectionViews时,一切都按预期工作,在选择分段控件的第一个按钮时显示UICollectionView对象。

@objc func changed() {
if segmentTime.selectedSegmentIndex == 0 {
self.dataCollectionViews.isHidden = false
let dataCollectionTop = NSLayoutConstraint(item: self.dataCollectionViews, attribute: .top, relatedBy: .equal, toItem: sortLabel, attribute: .bottom, multiplier: 1.0, constant: 10)
let dataCollectionLeft = NSLayoutConstraint(item: self.dataCollectionViews, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 10)
let dataCollectionRight = NSLayoutConstraint(item: self.dataCollectionViews, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: -10)
let dataCollectionHeight = NSLayoutConstraint(item: self.dataCollectionViews, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 520/812, constant: 0)
let dataCollectionWidth = NSLayoutConstraint(item: self.dataCollectionViews, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 355/375, constant: 0)
NSLayoutConstraint.activate([dataCollectionLeft, dataCollectionRight, dataCollectionHeight, dataCollectionWidth, dataCollectionTop])
}
if segmentTime.selectedSegmentIndex == 1 {

}
if segmentTime.selectedSegmentIndex == 2 {

}
}

我很想尝试在属性初始值设定项中设置 dataCollectionViews 对象,但我知道这是不可能的,但似乎dataCollectionViews第一次尝试时需要用UICollectionViewFlowLayout()初始化。还有什么其他选择?

这样的事情怎么样?

private lazy var collectionView: UICollectionView = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 188.0, height: 268.0)
let result: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
result.register(CellClass.self, forCellWithReuseIdentifier: "cell")
result.dataSource = self
result.delegate = self
return result
}()

相关内容

最新更新