簡體   English   中英

如何以編程方式在Swift 3中將UILabel添加到UICollectionViewCell

[英]How to programmatically add a UILabel to UICollectionViewCell in Swift 3

我有幾個UICollectionViewCells,我想以編程方式向單元格添加兩個標簽。 我怎么能以正確的方式做到這一點?

在您的單元類中,將其定義為全局。

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)
        }
}

您可以使用關鍵字google: customize table view cell

這是你如何做到的:

首先,您需要創建一個UICollectionViewCell的子類, UICollectionViewCell所示:

//我將使用YourCellClass作為custom cell's class

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM