简体   繁体   English

自定义布局UICollectionView swift

[英]Custom layout UICollectionView swift

I am trying to achieve a custom layout like this one : 我正在尝试实现这样的自定义布局:

想要布局

I am trying to implement it via a UICollectionView. 我试图通过UICollectionView实现它。 First I use this code to have the desired size : 首先,我使用此代码来获得所需的大小:

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
        return CGSizeMake((collectionView.frame.size.width / 2) - 2 , (collectionView.frame.size.height / 3) - 2)
}

It's working fine. 一切正常。

The problem is that my picture is not properly centered. 问题是我的图片没有正确居中。 I did it this way : 我是这样做的:

情节提要中的约束

Let me explain : 让我解释 :

  1. One constraint to align the center of the uiimage on X 一种约束以在X上对齐uiimage的中心
  2. One constraint to do the same thing on Y 在Y上做相同事情的一个约束
  3. One constraint to keep the image ratio 保持图像比例的一种约束
  4. One constrain to say that the height of the image is 70% of the cell height 可以说图像的高度是像元高度的70%

    And the result is very not the one expected : 结果非常不理想:

布局的实际结果

i did it using custom layout. 我做到了使用自定义布局。

    let collLayout:UICollectionViewFlowLayout = layout as! UICollectionViewFlowLayout
    collLayout.scrollDirection = .Vertical
    collLayout.minimumInteritemSpacing = 10
    let width = (frame.size.width - 3*collLayout.minimumInteritemSpacing)*0.5

    collLayout.itemSize = CGSizeMake(width, width)

    collLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)

And then initialize your collection view with this custom layout. 然后使用此自定义布局初始化您的集合视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM