ios - 使用自动布局在 CollectionView 的 CollectionViewCell 中自动调整图像大小

标签 ios swift autolayout uicollectionview

我有一个带有水平 UICollectionViewFlowLayout 的 collectionView。

Here is the layout:

我正在努力实现:

如果设备方向是纵向,UIImageView 宽度将等于 view.width 并自动计算高度(就像自动布局通常发生的那样)。横向模式也一样。 示例 - Iphone 上的标准照片应用。

不幸的是,我不知道如何使用 autoLayout 实现它。我对 UIImageView 设置了约束,使其大小与单元格相等。但看起来销售本身无法固定到父 View 。

阅读类似的问题后,看起来必须使用

以编程方式调整单元格的大小
func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {



return CGSize(width: width, height: height)

}

我被卡住了,因为我知道屏幕的宽度,但不知道如何动态计算高度。

关于图片高度:

我的图像声明如下:

var pageImages = [UIImage]()

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: ImageDetailViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ImageDetailViewCell


    let curr = indexPath.row
    let imgName = data[albumNumber][curr]["image"]

    cell.DetailImageView.image = UIImage(named: imgName!)


    return cell
}

最佳答案

如果您使用正确的 UIImageView 调整大小设置(例如,纵横比/填充),那么您只需将单元格的高度设置为您的 collectionView 的高度(您将获得一个指向它的指针作为...sizeForItemAtIndexPath... 方法参数)高度。之后您还应该在单元格上调用 - layoutIfNeeded 方法。

关于ios - 使用自动布局在 CollectionView 的 CollectionViewCell 中自动调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458148/

相关文章:

iOS 通用链接不适用于 HTTP

iphone - 带有 pushViewController 动画的 popViewController

ios - Swift 变量作用域问题

ios - 如何调整 super View 的大小以适应自动布局的所有 subview ?

swift - 从自定义 UIView 类设置 View 宽度约束不更新框架

ios - 从 UITextView 中取出 CGRect

iphone - navigationBar 和 MPMoviePlayerController 的异常行为。 iOS 中的错误还是我的错误?

ios - 如何在其他类的 ViewDidAppear 和 ViewDidDisappear 中插入代码

ios - Swift:如何使SegmentedControl通知通过滑动完成的值变化?

iOS UITableView 自定义 RowHeightt