我的應用程序需要幾個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