菜鸟教程小白 发表于 2022-12-11 16:52:13

ios - UICollectionView,第一次加载时图像大小不正确


                                            <p><p>我有一个非常简单的演示,它使用 UICollectionView 来显示图片列表,我使用了一个自定义单元格类,它包含一个 UIImage 和一个标签,如下所示,没有约束。</p>

<p> <a href="/image/gCfVQ.png" rel="noreferrer noopener nofollow"><img src="/image/gCfVQ.png" alt="customize cell on storyboard"/></a> </p>

<p>然后我在代码中设置单元格的大小,如下所示。每行有 3 列。所有边距都设置为 10。</p>

<pre><code>// Calculate size of cell
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                               sizeForItemAtIndexPath indexPath: NSIndexPath) -&gt; CGSize {
      let totalSpace = marginLeft + marginRight + (colomnSpacing * CGFloat(numberOfItemsPerRow - 1))
      let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))

      // 20 is for label height.
      return CGSize(width: size, height: size + 20)
    }

    // Section margin, if you only have one section, then this is the CollectionView&#39;s margin.
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -&gt; UIEdgeInsets {
      return UIEdgeInsets(top: marginTop, left: marginLeft, bottom: marginBottom, right: marginRight) // top, left, bottom, right.
    }

    // Set row spacing
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -&gt; CGFloat {
      return rowSpacing
    }

    // Set column spacing
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -&gt; CGFloat {
      return colomnSpacing
    }
</code></pre>

<p>这是用于设置图像和标签大小的代码。图像的宽度为屏幕宽度的 1/3(不包括列空间),高度等于宽度。标签宽度等于图片宽度,标签高度设置为20。</p>

<pre><code>override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell {

      let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SearchImageCell

      // Set image size
      cell.imageView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height - 20)
      cell.imageView.contentMode = .ScaleAspectFill


      let currentItem = self.responseArray
      let imageUrl = currentItem[&#34;imgurl&#34;] as? String
      let url = NSURL(string: imageUrl!)

      // Load the image
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let data = NSData(contentsOfURL: url!)
            dispatch_async(dispatch_get_main_queue(), {
                cell.imageView.image = UIImage(data: data!)
            })
      }

      // Set label size
      cell.imageDesc.frame = CGRect(x: 0, y: cell.imageView.frame.height, width: cell.frame.width, height: 20)

      let shujia = currentItem[&#34;shujia&#34;] as? String
      cell.imageDesc.text = shujia!
      cell.imageDesc.font = cell.imageDesc.font.fontWithSize(14)
      cell.imageDesc.textAlignment = .Center

      return cell
    }
</code></pre>

<p><strong>问题是:</strong></p>

<p>当我第一次加载图像时,图像的大小不正确,如下所示,您可以看到图像的高度占据了整个单元格的高度,并且标签没有显示出来。 </p>

<p> <a href="/image/qx6VE.png" rel="noreferrer noopener nofollow"><img src="/image/qx6VE.png" alt="enter image description here"/></a> </p>

<p>但是,当我向下和向上滚动时(这使得单元格被重复使用),图像被调整大小,我得到了正确的结果,这就是我想要的!</p>

<p> <a href="/image/Nswi3.png" rel="noreferrer noopener nofollow"><img src="/image/Nswi3.png" alt="enter image description here"/></a> </p>

<p>我尝试添加一些调试代码来打印单元格/图像/标签的大小,似乎所有大小都是正确的。 </p>

<pre><code>cell width:100.0
cell height:120.0
image width:100.0
image height:100.0
label width:100.0
label height:20.0
</code></pre>

<p>那么,怎么了?</p>

<p>关于 SO( <a href="https://stackoverflow.com/questions/32593117/uicollectionviewcell-content-wrong-size-on-first-load" rel="noreferrer noopener nofollow">here</a> , <a href="https://stackoverflow.com/questions/28269452/subview-frame-is-incorrect-when-creating-uicollectionviewcell" rel="noreferrer noopener nofollow">here</a> ) 有一些类似的问题,但答案对我不起作用,例如 </p>

<pre><code>1. cell.layoutIfNeeded()
2. self.collectionViewLayout.invalidateLayout()
3. self.collectionView?.layoutIfNeeded()
</code></pre>

<p>请帮忙,如果您需要更多代码,请告诉我。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>为您的 <code>image view</code> 和 <code>label</code> 设置 <code>translatesAutoresizingMaskIntoConstraints</code> 为 true。也许它有效。</p>

<h2>注意:使用<code>IB</code>时会设置为false</h2></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UICollectionView,第一次加载时图像大小不正确,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38128580/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38128580/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UICollectionView,第一次加载时图像大小不正确