如何在Swift 3中以编程方式向UICollectionViewCell添加UILabel

4

我有几个UICollectionViewCells,我想通过编程方式向这些单元格添加两个标签。正确的方法是什么?


添加它从cellForRowAtIndexPath。 - Patel Jigar
2个回答

2

在你的单元格类中将其定义为全局。

class YourCollectionViewCell: UICollectionViewCell {

        var titleLabel:UILabel = {
            let label = UILabel(frame: CGRect(x:100, y: 30, width: UIScreen.main.bounds.width , height: 40))
            label.textAlignment = .left
            label.lineBreakMode = .byWordWrapping
            label.numberOfLines = 0
            return label
        }()

        override init(frame: CGRect) {
            super.init(frame: frame)
            self.addSubview(self.titleLabel)
        }
}

我正在尝试将标签添加到UICollectionViewCells而不是视图。 - fellowProgrammer
这已经是UICollectionViewCells了,我会分享所有的代码,这样就会有意义。 - Özgür Ersil

-2
你可以使用关键字“自定义表格视图单元格”在谷歌上进行搜索。
下面是实现方法:
首先,你需要创建一个继承自UICollectionViewCell的子类,代码如下:
// 我将使用YourCellClass作为你的自定义单元格类名
class YourCellClass: UITableViewCell {
// Your can add your label to this Cell
// Review @Özgür Ersil's code above
}

接下来,您需要将此类注册到您的表视图中。这个类必须有一个标识符。

tableView.register(YourCellClass.self, forCellReuseIdentifier: "cellId")

然后设置您的表视图的datasource。在 tableView:cellForRowAtIndexPath 中添加以下代码以获取您的单元格类的实例,并将其返回为您的表视图行。

let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell

这是为了创建UITableViewCell,而不是将UILabel添加到UICollectionViewCell中。 - Azam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接