我正在尝试制作一个简单的collectionView,由于某种原因,它根本没有显示。 我通过我创建的字符串列表(页面)将图像设置为我创建的一些自定义单元格(ProfileCells)。 问题在于不仅不显示单元格,而且集合视图也没有显示(我将背景设置为绿色进行测试)
extension ProfileController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ProfileCell
let page = pages[indexPath.item]
print("something",page)
cell.setImage(image: page)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
print (CGSize(width: view.frame.width, height: view.frame.height))
return CGSize(width: view.frame.width, height: view.frame.height)
}
}
“ loginButton”只是我要引用的虚拟图像,出现在Collectionview单元格中。
let cellId = "cellId"
let pages: [String] = {
let firstPage = "loginButton"
let secondPage = "loginButton"
let thirdPage = "loginButton"
return [firstPage,secondPage,thirdPage]
}()
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.headerReferenceSize = CGSize.zero
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.green
cv.dataSource = self
cv.delegate = self
cv.isPagingEnabled = true
cv.showsHorizontalScrollIndicator = false
cv.showsVerticalScrollIndicator = false
return cv
}()
collectionView是我创建的stackview的子视图(为简洁起见,此处未显示),即使stackView内部的所有其他子视图都起作用
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(stackView)
collectionView.register(ProfileCell.self, forCellWithReuseIdentifier: cellId)
}
这是我为CollectionViewCells制作的Custom类
class ProfileCell: UICollectionViewCell{
//Integrate the page class into collectionviewcell
var image: String?
func setImage(image: String) {
imageView.image = UIImage(named:image)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
//Here I select the image I want to use in collectionview
var imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.backgroundColor = UIColor.gray
iv.clipsToBounds = true
return iv
}()
//Setting up all views within collectionview
func setupViews() {
backgroundColor = UIColor.gray
addSubview(imageView)
imageView.anchorWithConstantsToTop(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
imageView.heightAnchor.constraint(equalToConstant: 50)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}