调整cellize以适合所有屏幕?

时间:2016-10-30 01:43:08

标签: ios swift xcode uicollectionview

我正在尝试将我的应用程序设置为所有屏幕尺寸,但我无法弄清楚如何操作。是否可以根据屏幕调整单元格的大小?目前我只是配置我的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列。我基本上只希望单元格大小适合正确的分辨率。

2 个答案:

答案 0 :(得分:2)

试用此代码:

从collectionView的协议实现以下功能:

  // 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布局原则。

enter image description here

答案 1 :(得分:0)

将collectionViewFlowLayout从界面构建器中的文档大纲拖到代码中以创建插座。在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)
    }