调整细胞大小适合所有屏幕?
我试图让我的应用程序适合所有screenize,但是我不知道如何。 是否可以根据屏幕调整单元格大小? 目前我只是configuration我的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,6s,6s)上有3列。 我基本上只是想要单元格大小适合正确的决议。
试试这个代码:
从collectionView的协议实现以下function:
// 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) }
…视图是你的控制器(超)视图
// 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布局原则。
将collectionViewFlowLayout从界面生成器中的文档大纲拖放到代码中以创build出口。 在ViewDidLayoutSubviews(当你知道你的框架宽度)设置宽度和高度:
//MARK: IBOutlet @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let width = collectionView.frame.size.width - collectionViewFlowLayout.sectionInset.left - collectionViewFlowLayout.sectionInset.right collectionViewFlowLayout.itemSize = CGSize(width: width, height: width) }