ImageView的约束不起作用

时间:2016-10-18 05:54:25

标签: ios uiimageview autolayout uicollectionview uicollectionviewcell

我已经使用AutoLayoutUICollectionView我面临的一个问题,我遇到了imageView的高度和宽度问题。我在我的UIImageView中添加了UICollectionViewCell,如下所示。

enter image description here

UICollectionViewDataSource方法。

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var width = Int((collectionView.frame.size.width - 30) / 4)
    if width % 2 != 0 {
        width += 1
    }        
    return CGSize(width: CGFloat(width), height: CGFloat(width))
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
    print("Cell Size - \(cell.bounds)")
    print("ImageView Size - \(cell.imageView.frame)")
    return cell
}

但是,当我运行此ImageView时,无论我将在哪个设备上运行70X70UICollectionViewCell的大小都在增加和减少{/ p>}。

在iPhone 6上,它将如下所示。

enter image description here

我已将backgroundColor的{​​{1}}设置为UIImageView的白色和红色,这样就可以让玩家了解Cell和ImageView大小的控制台日志,如下所示。

UICollectionViewCell

请任何人帮我看看为什么imageView大小没有根据Cell Size - (0.0, 0.0, 86.0, 86.0) ImageView Size - (5.0, 5.0, 70.0, 70.0) Cell Size - (0.0, 0.0, 86.0, 86.0) ImageView Size - (5.0, 5.0, 70.0, 70.0) 增加或减少。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

在研究了一下之后,我想出了以下方法来解决AutoLayoutUICollectionViewCell的问题。来自Xcode 6 CollectionViewCell未在界面构建器中显示contentView,因此在awakeFromNib单元格中我设置了autoresizingMask,它就像魅力一样。

class CustomCell: UICollectionViewCell {
    @IBOutlet var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        //Below line solved my problem
        self.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    }
}

答案 1 :(得分:1)

在集合视图的大小检查器中,将“估计大小”设置为“无”

答案 2 :(得分:0)

您需要设置约束,如下面的屏幕截图; enter image description here

答案 3 :(得分:-1)

水平居中和垂直居中当您的图像视图为图钉视图指定(顶部,底部,前导和尾随)时,不应存在约束。

水平移除中心和垂直居中约束 或者Top,Bottom,Leading&尾随并给出相等的宽度和高度作为父级以及中心垂直和水平 y。

似乎水平移动中心和垂直居中约束会解决您的问题,请尝试一下。

希望有所帮助。 祝你好运。