您可以从下面的代码中看到ViewDidLoad()
中已经设置了布局参数,但这给了我一个错误:
由于未捕获的异常而终止应用程序 “ NSInvalidArgumentException”,原因:“ UICollectionView必须为 使用非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()
进行初始化。还有什么其他选择?
答案 0 :(得分:1)
这样的事情怎么样?
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
}()