[英]Constraints in collectionView
我希望在collectionView单元格中具有动态的宽度和高度,因此每个屏幕上只有2个单元格。 距顶部,左侧,右侧及其之间的距离为10px。
例:
如果我有320像素的宽度(屏幕),我希望每个单元格为145像素,那么它应该是左侧的10像素+145(单元格)+ 10像素之间的宽度+ 145(第二个单元格)+右侧的10像素。
使您的控制器符合UICollectionViewDelegateFlowLayout
协议并实现以下方法:
import UIKit
class ViewController: UIViewController
{
let numberOfCells = 9
let kCellHeight : CGFloat = 100
let kLineSpacing : CGFloat = 10
let kInset : CGFloat = 10
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad()
{
super.viewDidLoad()
}
}
extension ViewController : UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return numberOfCells
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sampleCell", for: indexPath)
return cell
}
}
extension ViewController : UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: (UIScreen.main.bounds.width - 2*kInset - kLineSpacing)/2, height: kCellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return kLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsets(top: kInset, left: kInset, bottom: kInset, right: kInset)
}
}
这是所附的屏幕截图:
您可以使用堆栈视图,也可以设置单元格的宽度约束并将其拖动到代码中以将常量设置为屏幕大小的一半。
另外,为什么在以下情况下直接在单元格上使用约束:
func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize
{
return CGSizeMake(width ,height);
}
使用以下代码:
func collectionView(collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath)-> CGSize {let width =(screenSize.width-30)/ 2 let height = width * AspectRatio // AspectRatio-someValue或将height作为常量返回CGSizeMake(width,height)}
这对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.