调整单元格大小以适应所有屏幕? [英] Adjust cellsize for fit all screens?
问题描述
我正在尝试使我的应用适应所有屏幕尺寸,但我不知道如何去做.是否可以根据屏幕调整单元格的大小?目前我只配置我的 UICollectionView 如下:
I'm trying to fit my app to all screensize, however I can't figure out how to. Is it possible to resize the cell depending on the screen? At the moment I just configure my UICollectionView as followed:
func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return fields.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FieldDistributionCollectionViewCell
cell.frame.size = CGSize(width: ?, height: ?)
return cell
}
有推荐的方法吗?还是我需要确定手机的版本并手动设置尺寸?在较小的屏幕(4、4s)上,我只想要 2 列,但在(5、5s、6、6s)上需要 3 列.我基本上只是希望单元格大小适合正确的分辨率.
Is there a recommended way? Or do I need to determine the version of the phone and set the size manually? On the smaller screen (4, 4s) I only want 2 columns, but 3 columns on the (5, 5s, 6, 6s). I basically just want the cell size to fit the right resolution.
推荐答案
试试这个代码:
从collectionView的协议中实现以下功能:
Implement the following functions from collectionView's protocol:
// cell size
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
// To get 1 column
return CGSize(width: view.frame.size.width, height: view.frame.size.width)
// To get 2 column
//return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)
// To get 3 column
// return CGSize(width: view.frame.size.width/3, height: view.frame.size.width/3)
// Toget 4 column
// return CGSize(width: view.frame.size.width/4, height: view.frame.size.width/4)
}
...view 是控制器的(超级)视图
...where view is your controller's (super) view
// inter-spacing
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
// line-spacing
func collectionView(collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
CollectionView 布局原理.
CollectionView layout principle.
这篇关于调整单元格大小以适应所有屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!