【问题标题】:UICollectionView Cell subview resizes after collectionView: cellForItemAtIndexPath is completeUICollectionView Cell 子视图在 collectionView: cellForItemAtIndexPath 完成后调整大小
【发布时间】:2016-08-19 17:44:47
【问题描述】:

我正在使用集合视图来显示个人资料图像和人名的集合。所以我的单元格有一个 UIImageView 和一个 UILabel 作为子视图。我正在使用 UICollectionViewDelegateFlowLayout 方法:

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

根据可用空间计算单元格的大小。

所有这些都运行良好。我在单元格中为我的子视图添加了约束,以便它们也相应地调整大小。

我遇到的问题是我希望我的 UIImageViews 是圆圈。在我应用该效果之前,似乎自动布局不会重新计算单元格的子视图大小。相反,当我计算 imageView 的cornerRadius 时,它仍然说 imageViews 的宽度是 114.0(这是故事板中的内容),无论单元格有多大。这会导致 iPhone 5s 上出现圆圈,但在任何更大的设备上只会出现圆角。这是我的代码:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PersonCell", forIndexPath: indexPath)

    configureCell(cell, atIndexPath: indexPath)

    return cell
}

func configureCell(cell: UICollectionViewCell, atIndexPath indexPath: NSIndexPath) {
    if let person = personAtIndexPath(indexPath) {
        let imageView = cell.viewWithTag(100) as! UIImageView
        let nameLabel = cell.viewWithTag(200) as! UILabel

        cell.contentView.frame = cell.bounds
        cell.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

        circularizeImageView(imageView)
        imageView.image = person.profileImage
        nameLabel.text = person.name


    }
}

func circularizeImageView(imageView: UIImageView) {
    imageView.layer.cornerRadius = (CGRectGetWidth(imageView.bounds) / 2)
    imageView.clipsToBounds = true
    imageView.layer.borderWidth = 2.0
    imageView.layer.borderColor = UIColor.whiteColor().CGColor
}

我在几个地方看到以前子视图根本不会像这里一样调整大小:UICollectionView cell subviews do not resize

我认为这不再是问题,但是我确实将修复添加到我的代码中,正如您在 configureCell() 中看到的那样,但它仍然没有帮助。

所以看起来这些子视图直到 cellForItemAtIndexPath 调用完成后才调整大小。关于我如何解决这个问题的任何想法?见截图:rounded corners on UIImageViews instead of complete circles

【问题讨论】:

    标签: ios autolayout uicollectionview uicollectionviewcell


    【解决方案1】:

    不要使用viewWithTag(),这是不好的做法。改为使用 UILabel 和 UIImageView public 或省略范围修饰符。

    UIImageView 是固定大小吗?如果是这样,您无需在每次重用单元格时都调用circularizeImageView()。相反,请在您的 UITableViewCell 子类中的 layoutSubviews() 中调用它。这也将为您提供imageView.bounds.height 的正确大小

    【讨论】:

    • 谢谢@bsmith11。那是我的问题。我没有对 UICollectionViewCell 进行子类化(这就是我使用 viewWithTag() 的原因)......到处都是错误的决定。现在我已经对单元格进行了子类化,并在 layoutSubviews() 中为该子类调用了 cicularizeImageView()。它工作得很好,而且我的代码更干净,因为我的 viewController 不再负责单元格的布局。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2019-01-01
    • 2013-02-24
    • 2014-12-09
    • 1970-01-01
    • 2015-12-29
    • 2015-06-16
    相关资源
    最近更新 更多