如何以编程方式设置集合视图的大小
问题描述:
我有一个集合视图,它形成了15 x 15的网格。我想将它的高度和宽度设置为包含它的视图高度的0.5(或几倍)。我在故事板中完成了此操作,并将纵横比设置为1:1。如何以编程方式设置集合视图的大小
我的问题是,当我旋转屏幕为横向网格是不再15×15
我可以直接在故事板例如设置高度300×300但我遇到问题,让它适合不同的设备。
答
您有此问题,因为横向模式下的高度低于纵向。所以,如果你设置的UICollectionView
宽度&高度限制等于(有一些乘数),以superview
它会自动改变它的大小,当你旋转装置
你可以做什么它在代码连接宽度&高度网点和集拨付值在viewDidLoad
方法
答
试试这个
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
尝试上面更新的代码 –
不行,我很害怕。此外,我的目标是1:1的宽高比 –