3 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
添加這2行
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
所以你有了:
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
這將刪除所有空格并為您提供網(wǎng)格布局:
在此處輸入圖片說明
如果希望第一列的寬度等于屏幕寬度,請(qǐng)?zhí)砑右韵鹿δ埽?/p>
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
網(wǎng)格布局現(xiàn)在看起來像(我還在第一個(gè)單元格中添加了藍(lán)色背景)

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
對(duì)于Swift 3和XCode 8來說,這可行。請(qǐng)按照以下步驟來實(shí)現(xiàn):
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
將此代碼放入viewDidLoad()函數(shù)。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
在某些情況下,設(shè)置UICollectionViewFlowLayoutin viewDidLoad或ViewWillAppear不影響collectionView。
設(shè)置UICollectionViewFlowLayoutin viewDidAppear可能會(huì)導(dǎo)致在運(yùn)行時(shí)看到像元大小的變化。
Swift 3中的另一個(gè)解決方案:
extension YourViewController : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = collectionView.bounds.width
return CGSize(width: collectionViewWidth/3, height: collectionViewWidth/3)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20
}
}
- 3 回答
- 0 關(guān)注
- 535 瀏覽
添加回答
舉報(bào)