简体   繁体   English

如何在没有自定义类的情况下将UILabel添加到UICollectionViewCell?

[英]How do you add a UILabel to a UICollectionViewCell without custom class?

I've dragged a UICollectionViewController to the main storyboard and created the corresponding class. 我已经将UICollectionViewController拖到主故事板上,并创建了相应的类。

在此处输入图片说明 I've named/connected everything in storyboard and view controller correctly. 我已经正确命名/连接了情节提要中的所有内容并正确地查看了控制器。

在此处输入图片说明 在此处输入图片说明

But I am unable to access objects I've placed in the UICollectionViewCell... for instance I can't set the text property on the UILabel. 但是我无法访问放置在UICollectionViewCell中的对象……例如,我无法在UILabel上设置text属性。

在此处输入图片说明

If I create a custom UICollectionViewCell class and create/connect the @IBOutlet to the UILabel everything works fine. 如果我创建一个自定义UICollectionViewCell类并将@IBOutlet创建/连接到UILabel,则一切正常。

But do I have to create this custom UICollectionViewCell class? 但是我是否必须创建此自定义UICollectionViewCell类?

It looks like the collection view is aware that a label has been added to the cell, based on the tree view in storyboard. 基于情节提要中的树状视图,看来集合视图已意识到已将标签添加到单元格。

I just want to add a label w/ some default text and want to avoid adding the extra file. 我只想添加带有一些默认文本的标签,并希望避免添加额外的文件。

You can do even without creating the custom class, by using the 'Tag' 您甚至可以通过使用'Tag'而无需创建自定义类来进行操作

For example, give the Tag '101' to your UICollectionView label as shown below. 例如,如下所示,将UICollectionView '赋予您的UICollectionView标签。

Then in your cellForRowAt method: 然后在您的cellForRowAt方法中:

let label = cell.viewWithTag(101) as! UILabel
label.text = "Hi"

在此处输入图片说明

Hope it helps! 希望能帮助到你!

UICollectionView does not have ready made cell templates like UITableView. UICollectionView没有像UITableView这样的现成单元格模板。 You will have to create your own class of UICollectionViewCell. 您将必须创建自己的UICollectionViewCell类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM