我的应用程序需要几个CollectionViews
,因此我决定以编程方式创建它们。我为每个单元添加了一个UILabel
,但是UILabel仅添加到随机cell
s,而其他单元不显示任何标签。以编程方式将UILabel添加到CollectionViewCells
如果我上下滚动文本标签随机在特定单元格内消失并重新出现在其他单元格上。 这里的问题是
的视觉描绘(注意标签消失而我向下滚动)
我需要所有单元,以显示textLabels。
这是我使用的代码:
我视图控制器
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 0 , y: 50 , width: 375 , height: 300)
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: frame , collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: NSStringFromClass(CustomCell.self))
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 250 }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CustomCell.self), for: indexPath) as! CustomCell
cell.nameLabel.text = "XYZ"
return cell
}
II自定单元
class CustomCell: UICollectionViewCell {
var nameLabel: UILabel!
override init(frame : CGRect) {
super.init(frame : frame)
nameLabel = UILabel(frame: self.frame)
nameLabel.textAlignment = .left
nameLabel.textColor = .black
contentView.addSubview(nameLabel)
contentView.backgroundColor = .red
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
是什么原因造成ü异常行为?我是否错误地设置了我的collectionView
?
func CollectionView(_ CollectionView:UICollectionView,heightForRowAt indexPath:IndexPath) - > CGFloat {。这是什么?这是如何返回UICollectionViewCell的大小https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview – 2017-09-03 12:13:21
我很抱歉,这是一个错字。我更新了代码。 – 6994
以编程方式创建UILabel需要您设置IB为您所做的所有属性,因此请参阅:https://stackoverflow.com/questions/17813121/programmatically-creating-uilabel另外,您是否尝试过UILabel到前面? 第二个问题,看起来像你的出队问题,尝试设置awakeFromNib方法内的标签。 – OhadM