我正在尝试自动调整集合视图单元格的大小。在iPhone 8中,设计还可以,但是当我尝试更换iPhone时(尤其是在iPhone SE上),电池无法自动调整大小,并且电池通常太大或太小。我正在
enter image description here扩展ViewController:UICollectionViewDataSource,UICollectionViewDelegate {
答案 0 :(得分:0)
添加UICollectionViewDelegateFlowLayout方法
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: value, height: value)
}
答案 1 :(得分:0)
这是由于您
之间的不匹配而发生的解决方案:-
添加UICollectionViewDelegateFlowLayout委托并添加这些方法并根据您的要求更新值:-
let edge : CGFloat = 10.0
let spacing : CGFloat = 10.0
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return spacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfColumn = 2
let collectionviewWidth = collectionView.frame.width
let bothEdge = CGFloat(edge + edge) // left + right
let excludingEdge = collectionviewWidth - bothEdge
let cellWidthExcludingSpaces = excludingEdge - ((noOfColumn-1) * spacing)
let finalCellWidth = cellWidthExcludingSpaces / noOfColumn
let height = finalCellWidth
return CGSize(width: finalCellWidth, height: height)
}
答案 2 :(得分:0)
如果您要尝试的就是这个
无论屏幕大小如何,我总是希望连续2个(或说n个)项目!
那么您需要UICollectionViewFlowLayout
您可以尝试以下代码
let itemSize = UIScreen.main.bounds.width/2 - 3
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = 3
layout.minimumLineSpacing = 3
collectionView.collectionViewLayout = layout
在上面的代码中,将 2 替换为以下行:
let itemSize = UIScreen.main.bounds.width / 2 -3
在单行中包含您想要的项目数
您可以将此代码放入viewDidLoad()
或viewDidAppear()
答案 3 :(得分:0)
尝试一下,它将起作用:
首先,您必须添加UICollectionViewDelegateFlowLayout
委托,然后使用以下委托方法,它对我来说很好。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 10
let collectionViewSize = collectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}
答案 4 :(得分:0)
Xcode 10 / Swift 4
实施以下方法,它会根据您拥有的屏幕自动调整大小。
// Collection View Layout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenWidth = UIScreen.main.bounds.width
return CGSize.init(width: (screenWidth-55) / 2, height: (screenWidth-55) / 2 * 1.481)
}