菜鸟教程小白 发表于 2022-12-11 18:30:05

ios - 编辑 CollectionViewCell 的宽度


                                            <p><p>我正在尝试编辑单元格的宽度,以便无论屏幕大小如何,我都会连续有 <code>score1.count</code> 个单元格。我用于收藏 View 的代码如下:</p>

<pre><code>func numberOfSections(in collectionView: UICollectionView) -&gt; Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
    return self.items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    cell.myLabel.text = String(self.items)

    return cell
}
</code></pre>

<p>这是针对单元格宽度的函数。</p>

<pre><code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -&gt; CGSize {
    let size = Int(self.view.frame.size.width)/(score1.count + 1)
    return CGSize(width: CGFloat(size), height: 80)
}
</code></pre>

<p>我花了很多时间查看不同的来源并尝试不同的东西,但 Collection View 从来没有正确数量的单元格。一个想法是,这可能是因为我在自动布局中设置了单元格大小,但是每当我去更改它时,xcode 就会崩溃。关于绕过自动布局的任何想法?或者如何改变自动布局?</p>

<p>谢谢!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>试试这个<br/></p>

<pre><code>extension YourViewController : UICollectionViewDelegateFlowLayout{

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {
    let rowItems:CGFloat = 4
    let padding:CGFloat = 2
    let width = (collectionView.bounds.width / rowItems) - padding //Change width as per your requirement
    let height = collectionView.bounds.height - (2 * padding)//Change height as per your requirement
    return CGSize(width: width, height: height)
}

}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 编辑 CollectionViewCell 的宽度,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45665846/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45665846/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 编辑 CollectionViewCell 的宽度