簡體   English   中英

cellForItemAt沒有在collectionView中調用

[英]cellForItemAt is not calling in collectionView

我有一個inputView,其中將顯示collectionView。 我為該inputView使用了自動布局。 運行應用程序時,將調用numberOfItemsInSection,但不調用cellForItemAt。 因此沒有顯示任何單元格。 使用約束我做錯了什么嗎? 我還創建了項目https://drive.google.com/file/d/0B5UHWsK1E6dSRDA5bmtSY2ZZbGs/view

ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    textField.inputView = InputPhotoView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 265))
    textField.becomeFirstResponder()
}

InputPhotoView.swift

class InputPhotoView: UIView {
let CellIdentifier = "Cell"
override init(frame: CGRect) {
    super.init(frame: frame)
    collectionView.dataSource = self
    collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CellIdentifier)
    setupViews()
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    fatalError("Not yet implented")
}
func setupViews() {
    self.backgroundColor = UIColor.brown
    self.addSubview(collectionView)
    setupConstraints()
}
func setupConstraints() {
    NSLayoutConstraint.activate([
        collectionView.leadingAnchor.constraint(equalTo: self.trailingAnchor, constant: 50),
        collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0),
        collectionView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0),
        collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0)
        ])
}
public lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.itemSize = CGSize(width: 100, height: 100)
    layout.minimumInteritemSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.contentInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    return collectionView
}()

} 數據源

extension InputPhotoView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print("number of items")
    return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CustomCell
    return cell
}

}

您的代碼具有約束沖突,因此collectionView不可見。 嘗試更改此行:

collectionView.leadingAnchor.constraint(equalTo: self.trailingAnchor, constant: 50)

對於這樣的事情:

collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 50)

暫無
暫無

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

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