我正在尝试让我的应用适合所有屏幕尺寸,但我不知道该怎么做。是否可以根据屏幕调整单元格的大小?目前我只是按如下方式配置我的 UICollectionView:
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 列。我基本上只希望像元大小适合正确的分辨率。
最佳答案
试试这个代码:
从 collectionView 的协议(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 是您 Controller 的( 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布局原理。
关于ios - 调整单元格大小以适合所有屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325327/