2017-08-01 106 views
0

我有一個集合視圖,它形成了15 x 15的網格。我想將它的高度和寬度設置爲包含它的視圖高度的0.5(或幾倍)。我在故事板中完成了此操作,並將縱橫比設置爲1:1。如何以編程方式設置集合視圖的大小

enter image description here

我的問題是,當我旋轉屏幕爲橫向網格是不再15×15

enter image description here

我可以直接在故事板例如設置高度300×300但我遇到問題,讓它適合不同的設備。

回答

0

您有此問題,因爲橫向模式下的高度低於縱向。所以,如果你設置的UICollectionView寬度&高度限制等於(有一些乘數),以superview它會自動改變它的大小,當你旋轉裝置

你可以做什麼它在代碼連接寬度&高度網點和集撥付值在viewDidLoad方法

0

您可以將相等寬度和相等高度約束添加到您的集合視圖中。然後將約束倍數修改爲0.5,如下圖所示 - enter image description here

+0

不行,我很害怕。此外,我的目標是1:1的寬高比 –

0

試試這個

extension MYViewController: UICollectionViewDelegateFlowLayout { 
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
     return CGSize(width: collectionView.frame.width/15, height: collectionView.frame.height/15) 
    } 
} 

添加這些行太

override func viewWillLayoutSubviews() { 
     guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { 
      super.viewWillLayoutSubviews() 
      return 
     } 
     flowLayout.invalidateLayout() 
     super.viewWillLayoutSubviews() 
    } 
+0

我試過這個並且不能使它工作 –

+0

嘗試上面更新的代碼 –

相關問題