如何以编程方式将 UILabel 添加到 Swift 中的 UICollectionViewCell 3
How to programmatically add a UILabel to UICollectionViewCell in Swift 3
我有几个 UICollectionView 单元格,我想以编程方式向单元格添加两个标签。我该如何以正确的方式做到这一点?
在您的单元格中 class 将其定义为全局。
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
的子class:
// 我将使用 YourCellClass
作为你的 custom cell's class
class YourCellClass: UITableViewCell {
// Your can add your label to this Cell
// Review @Özgür Ersil's code above
}
然后,您必须将此 class 注册到您的 table 视图。此 class 必须有标识符
tableView.register(YourCellClass.self, forCellReuseIdentifier: "cellId")
然后设置 table 视图的 datasource
。并在 tableView:cellForRowAtIndexPath
中添加以下代码以获取单元格实例 Class 和 return 它用于 table 视图行
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell
我有几个 UICollectionView 单元格,我想以编程方式向单元格添加两个标签。我该如何以正确的方式做到这一点?
在您的单元格中 class 将其定义为全局。
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
的子class:
// 我将使用 YourCellClass
作为你的 custom cell's class
class YourCellClass: UITableViewCell {
// Your can add your label to this Cell
// Review @Özgür Ersil's code above
}
然后,您必须将此 class 注册到您的 table 视图。此 class 必须有标识符
tableView.register(YourCellClass.self, forCellReuseIdentifier: "cellId")
然后设置 table 视图的 datasource
。并在 tableView:cellForRowAtIndexPath
中添加以下代码以获取单元格实例 Class 和 return 它用于 table 视图行
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell