如何使用集合视图的高度将UICollectionView项调整为方形大小?

时间:2017-03-18 17:12:02

标签: ios swift autolayout uicollectionview

集合视图位于屏幕的上半部分。集合视图是水平的,有一行。

该行可以包含多个集合视图单元格。

里面的每个单元都有UIImageView。 UIImageView意味着包含UIImage。

UIImage是一张照片。照片的大小可能不同,但在集合视图单元格中,它必须与宽高比1:1进行平方。

问题是使集合视图单元格为方形大小,其中正方形的边应该等于collectionView的高度。并且UIImageView应该占用集合视图单元格的整个空间,使UIImage平方。

UIImageView的约束设置比为1:1;以及收集单元的顶部,前导和底部。

收集单元格的大小以编程方式计算:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let size = collectionView.bounds.size.height

    return CGSize(width: size, height: size)
}

我在调试器中收到以下错误:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x6180000968f0 h=--& v=--& UIView:0x7f8c3f61e940.width == 217   (active)>",
    "<NSAutoresizingMaskLayoutConstraint:0x618000096990 h=--& v=--& UIView:0x7f8c3f61e940.height == 100   (active)>",
    "<NSLayoutConstraint:0x618000096030 UIImageView:0x7f8c3f61eae0.width == UIImageView:0x7f8c3f61eae0.height   (active)>",
    "<NSLayoutConstraint:0x618000096120 H:[UIImageView:0x7f8c3f61eae0]-(0)-|   (active, names: '|':UIView:0x7f8c3f61e940 )>",
    "<NSLayoutConstraint:0x618000096170 V:[UIImageView:0x7f8c3f61eae0]-(0)-|   (active, names: '|':UIView:0x7f8c3f61e940 )>",
    "<NSLayoutConstraint:0x6180000961c0 H:|-(0)-[UIImageView:0x7f8c3f61eae0]   (active, names: '|':UIView:0x7f8c3f61e940 )>",
    "<NSLayoutConstraint:0x618000096210 V:|-(0)-[UIImageView:0x7f8c3f61eae0]   (active, names: '|':UIView:0x7f8c3f61e940 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x618000096030 UIImageView:0x7f8c3f61eae0.width == UIImageView:0x7f8c3f61eae0.height   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

如何让它发挥作用?

1 个答案:

答案 0 :(得分:1)

您不需要宽高比约束和正确约束。一个就够了。但是,从逻辑上讲,如果你有两者,如果你的尺寸计算是正确的,它们不应该发生冲突。

你的计算看起来不错。因此,可能会影响您的计算的是(标题大小,页脚大小,间距插入)

  

可能影响这一点的另一件事是重新加载集合视图数据   在uiviews完成布局之前的viewDidLoad上。

enter image description here