ios - Swift:collectionView 单元格
<p><p>我创建 <code>collectionView</code> 我有 3 个单元格。我希望我的单元格在所有设备的所有屏幕上看起来都像这样:</p>
<p> <a href="/image/CTxvv.png" rel="noreferrer noopener nofollow"><img src="/image/CTxvv.png" alt="enter image description here"/></a> </p>
<p>但我有 iPad 的这个结果。</p>
<p> <a href="/image/Bo2ld.png" rel="noreferrer noopener nofollow"><img src="/image/Bo2ld.png" alt="enter image description here"/></a> </p>
<p>如何解决?</p>
<p><strong>更新</strong></p>
<p>我在 <code>UIViewController</code> 中添加 <code>collectionView</code>。我对 <code>collectionView</code> 有这个限制:</p>
<p> <a href="/image/hSqxA.png" rel="noreferrer noopener nofollow"><img src="/image/hSqxA.png" alt="enter image description here"/></a> </p>
<p>调整我的单元格大小:</p>
<p> <a href="/image/i05G8.png" rel="noreferrer noopener nofollow"><img src="/image/i05G8.png" alt="enter image description here"/></a> </p>
<p>代码:</p>
<pre><code>func numberOfSections(in collectionView: UICollectionView) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow: CGFloat = 3
let itemWidth = (collectionView.bounds.width / itemsPerRow)
let itemHeight = itemWidth * 1.5
return CGSize(width: itemWidth, height: itemHeight)
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您需要自适应地更改单元格大小,否则该大小将不适用于所有屏幕尺寸。</p>
<p>你有你的函数,你返回单元格大小:</p>
<pre><code>return CGSize(width: 182, height: 275)
</code></pre>
<p>相反,让它像这样自适应:</p>
<pre><code>return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)
</code></pre>
<p>或者,为了中间有间隙,创建一个偏移量:</p>
<pre><code>let offset = 10
let width = self.view.frame.width - offset * 4 // 4 gaps
let height = self.view.frame.height - offset * 2 // 2 gaps
return CGSize(width: width / 3, height: height) // Divide into equally-sized cells
</code></pre>
<p>当然,<code>self.view</code> 可以替换为您希望单元格适合的任何容器。</p></p>
<p style="font-size: 20px;">关于ios - Swift:collectionView 单元格,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/51121988/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/51121988/
</a>
</p>
页:
[1]