【问题标题】:Simply using storyboard, constraints to set size of cell in UICollectionView只需使用情节提要、约束来设置 UICollectionView 中的单元格大小
【发布时间】:2016-10-28 03:28:58
【问题描述】:

这是一个 UICollectionView,紫色的单元格:

很简单,我希望单元格为集合视图宽度的 1/2。 (所以待定,它将是集合视图中的两行单元格排列。)

(集合视图只是全屏,所以每个单元格都是屏幕宽度的一半。)

你如何在故事板中做到这一点?

如果我尝试以正常方式控制拖动,它基本上不起作用。

这些是简单的完全静态的单元格(不是动态的)。


对于任何在这里搜索的人,为了节省您的时间:这正是(2016 年)制作两个 UICollectionView 布局的最简单方法;细胞之间没有间隙。

// Two - two-across UICollectionView
// use a completely standard UIViewController on the storyboard,
// likely change scroll direction to vertical.
// name the cell identifier "cellTwo" on the storyboard
import UIKit
class Two:UICollectionViewController
    {
    override func viewDidLoad()
        {
        super.viewDidLoad()

        let w = collectionView!.bounds.width / 2.0

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.itemSize = CGSize(width:w,height:w)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0

        collectionView!.collectionViewLayout = layout

        // Note!! DO NOT!!! register if using a storyboard cell!!
        // do NOT do this:
        // self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
        { return 1 }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
        {  return 5 }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
        {
        return collectionView.dequeueReusableCellWithReuseIdentifier("cellTwo", forIndexPath: indexPath)
        }
    }

【问题讨论】:

标签: ios cocoa-touch uicollectionview uistoryboard nslayoutconstraint


【解决方案1】:

你不能在情节提要中做到这一点。直到运行时才知道集合视图宽度,并且集合视图单元格不在自动布局下,因此您无法表达“1/2 宽度”的概念。 (如果您事先知道集合视图的宽度,则可以使用情节提要中的流布局来绝对设置单元格大小,方法是在头脑中划分;但您不知道,因为宽度因设备而异.)

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 2014-03-30
    • 2018-01-13
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2012-09-27
    相关资源
    最近更新 更多