我在一个集合视图中有两个单元格。它们都有不同的尺寸,但由于某些原因,在运行时,两个单元格似乎都具有相同的尺寸。
这是我的设置:
internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if cellType == .books {
return books.count
} else if cellType == .spotlights {
return spotlights.count
} else {
return 0
}
}
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if cellType == .books {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "booksCollectionCell", for: indexPath) as! BooksCollectionCell
let bookTitle = books[indexPath.item].title
let authors = books[indexPath.item].authors
cell.configureCell(title: bookTitle, authorNames: authors)
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "spotlightsCollectionCell", for: indexPath) as! spotlightsCollectionViewCell
cell.configureCell(image: #imageLiteral(resourceName: "testImage"))
return cell
}
}
这是我的故事板截图:
这是为collectionView设置的:
编辑:所以我设法通过将此代码放在cellForItem中来获取somwhere(感谢cpatmulloy):
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: 180.0, height: 130.0)
但是,这是结果(查看tableview中的最后一个单元格):
答案 0 :(得分:1)
尝试在cellForItemAtIndex路径功能中明确设置单元格的高度和宽度。
请务必自己设置这些示例属性(即bookCellWidth)
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if cellType == .books {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "booksCollectionCell", for: indexPath) as! BooksCollectionCell
let bookTitle = books[indexPath.item].title
let authors = books[indexPath.item].authors
cell.configureCell(title: bookTitle, authorNames: authors)
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: bookCellWidth, height: bookCellHeight)
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "spotlightsCollectionCell", for: indexPath) as! spotlightsCollectionViewCell
cell.configureCell(image: #imageLiteral(resourceName: "testImage"))
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: spotlightCellWidth, height: spotlightCellHeight)
return cell
}
}
答案 1 :(得分:0)
好的,所以我设法解决了它!
首先我将UICollectionViewDelegateFlowLayout
添加到cell
类,然后:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if cellType == .spotlights {
return CGSize(width: 250.0, height: 180.0)
} else {
return (collectionViewLayout as! UICollectionViewFlowLayout).itemSize
}
}