SizeForItemAtIndexPath:获取标准尺寸的项目

时间:2017-09-17 15:26:19

标签: swift uicollectionview

我在具有两个集合视图的视图控制器中使用sizeForItemAtIndexPath函数。

如何在sizeForItemAtIndexPath函数中排除一个集合视图,或者如何在不更改任何内容的情况下获取原始单元格大小?

2 个答案:

答案 0 :(得分:2)

  • 排除一个集合视图

     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
          // to exclude one collection view
          if collectionView == collectionViewOne {}// first
         if collectionView.tag == number(you set before){}// second
    
         // to get the original cell size without changing anything
         //let yourSize = collectionViewLayout.itemSize
         //return collectionViewLayout.itemSize   // if you have set it globally, 
        /*
         But you can not get it, because itemSize is a property of UICollectionViewFlowLayout.
    
         And you can't cast collectionViewLayout to UICollectionViewFlowLayout Class which is kind of UICollectionViewLayout Class .
    
       Thats not how inheritance works.
      */    
    }
    
  • 获取原始单元格大小而不更改任何内容

    let indexPath = IndexPath(item: number(you choose), section: number(you choose, 0 or 1))
    let layout = UICollectionViewFlowLayout() // you set
    // got the size
    // more generally, if you have set layout per item through delegate.
    let size = self.collectionView(collectionViewOne, layout: layout, sizeForItemAtIndexPath: indexPath)
    // or try this ,if you have configured globally
    let itemSize = layout.itemSize
    

答案 1 :(得分:1)

假设您正在使用故事板,则可以将每个集合视图作为插座连接到视图控制器。 E.g

@IBOutlet weak var collectionViewOne: UICollectionView!
@IBOutlet weak var collectionViewTwo: UICollectionView!

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  if collectionView == collectionViewOne {
    // Do nothing, and set default size.
    return layout.itemSize
  } else {
    //Set size here along with other setup.
    return CGSize(width: 150, height: 150)
  }
}