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

问题描述:

我有几个UICollectionViewCells,我想以编程方式将两个标签添加到单元格中。我如何以正确的方式来做到这一点?如何在Swift 3中以编程方式向UICollectionViewCell添加UILabel

+0

从的cellForRowAtIndexPath –

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

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

我想要的标签添加到UICollectionViewCells不认为 – fellowProgrammer

+0

这是UICollectionViewCells已经添加它,我将分享所有的代码,这将是有意义的 –

你可以用关键字在Google上:customize table view cell

这是你如何做到这一点:首先,你需要创建的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 
+0

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