如何以编程方式添加 UICollectionViewLayout? [英] How to add an UICollectionViewLayout programmatically?

查看:34
本文介绍了如何以编程方式添加 UICollectionViewLayout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式设置 UICollectionViewLayout.我正在使用 UICollectionView 也没有使用故事板,也没有设置它的约束.

I'm trying to setup a UICollectionViewLayout programmatically. I'm using a UICollectionView also without using storyboards, as well as settings its constraints.

我遵循了 Ray Wenderlich 教程主题进行了一些更改以使代码适应 Swift 3(正如 AZCoder2 所做的 https://github.com/AZCoder2/Pinterest).

I've followed Ray Wenderlich tutorial on the subject with some changes to adapt the code to Swift 3 (as AZCoder2 did https://github.com/AZCoder2/Pinterest).

由于所有这些示例都使用故事板,我还引入了一些更改来创建 UICollectionView 及其 UICollectionViewLayout:

Since all these examples uses storyboards, I've also introduced some changes to create the UICollectionView and its UICollectionViewLayout:

collectionViewLayout = PinterestLayout()
collectionViewLayout.delegate = self
collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: collectionViewLayout)

结果:我什么也看不见.如果我将 UICollectionViewLayout 更改为 Apple 提供的(UICollectionViewFlowLayout),至少我可以看到带有内容的单元格.如果我实施一些更改并使用故事板,一切都很好,但这不是我想要的方式.整个视图以编程方式制作,集合视图是其中的一部分.

The result: I can't see anything. If I change the UICollectionViewLayout with the one that Apple provides (UICollectionViewFlowLayout), at least I can see the cells with their content. If I implement some changes and use the storyboard, everything works great but it's not the way I want to accomplish this. The whole view is made programmatically and the collection view is a part of it.

我错过了什么?这与我实例化 UICollectionViewLayout 的方式有关吗?我是否必须注册某些内容(例如,因为我需要注册可重用单元)?

What am I missing? Is it something to do with the way I instantiate the UICollectionViewLayout? Do I have to register something (for example, as I need to register the reusable cell)?

推荐答案

你如何只创建一个变量,像这样为你创建流布局

How about you just create a variable that creates your flow layout for you like this

var flowLayout: UICollectionViewFlowLayout {
    let _flowLayout = UICollectionViewFlowLayout()

    // edit properties here
    _flowLayout.itemSize = CGSize(width: 98, height: 134)
    _flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5)
    _flowLayout.scrollDirection = UICollectionViewScrollDirection.horizontal
    _flowLayout.minimumInteritemSpacing = 0.0
    // edit properties here

    return _flowLayout
}

然后你可以通过调用变量来设置它.

And then you can set it by calling the variable.

self.collectionView.collectionViewLayout = flowLayout // after initializing it another way
// or
UICollectionView(frame: .zero, collectionViewLayout: flowLayout)

这篇关于如何以编程方式添加 UICollectionViewLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆