简体   繁体   English

以编程方式更改集合视图约束

[英]Change collection view constraints programmatically

I have create a collection view in my storyboard and add constraints. 我在情节提要中创建了一个集合视图并添加了约束。 Now I need to change the collection view constraint for a specific condition and I want to do it programmatically in my class. 现在,我需要针对特定​​条件更改集合视图约束,我想以编程方式在我的课程中进行操作。 I have an IBOutlet for the collection view. 我有一个IBOutlet用于集合视图。 What parameter needs to be changed? 需要更改什么参数?

  1. Add the constraints normally in the collection view 通常在集合视图中添加约束
  2. Select the constraint you want to modify, hold Control and drag to your class 选择要修改的约束,按住Control并拖动到您的班级
  3. When you want your constraint to be changed, type nameOfYourConstraint.constant = 100 // Int 当您希望更改约束时,键入nameOfYourConstraint.constant = 100 // Int

First create IBOutlet of constraints required to changed by dragging to ViewController 首先创建IBOutlet ,将其拖动到ViewController来更改需要更改的约束

The constant value needs to be cahnged, eg: constant量值需要进行调整,例如:

self.outlet.constant = 50

Don't forget to call self.view.layoutIfNeeded after modifying the constant. 不要忘记在修改常量后调用self.view.layoutIfNeeded

您需要创建约束的IBOutlet,并根据您的条件更新约束值。

By using UICollectionViewFlowLayout,you can easily change the layout of collection view. 通过使用UICollectionViewFlowLayout,可以轻松更改集合视图的布局。

    let layout = UICollectionViewFlowLayout()
    collectionView.collectionViewLayout = layout
    layout.sectionInset = UIEdgeInsets(top:0, 
    left:0,bottom:0,right:0)
    let itemWidth:CGFloat = (UIScreen.main.bounds.width)/2
    layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0

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

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