Достичь CollectionViewCell в Xib с программно - PullRequest
0 голосов
/ 05 июля 2018

Я создал Xib-файл и вызвал ViewController. Также я создаю CollectionView в Xib-файле. И теперь я хочу добраться до CollectionViewCell для отображения ячеек.

class ProductVC: UIViewController {

var collection:UICollectionView!
override func viewDidLoad() {
    super.viewDidLoad()

    let productView : ProductDetailView = UIView.fromNib()
    productView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(productView)

    collection = productView.collectionView
    collection.register(UINib(nibName: "TagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagCollectionViewCell")

    productView.topAnchor.constraint(equalTo: view.safeTopAnchor).isActive = true
    productView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
    productView.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height).isActive = true
}
}

class ProductDetailView: UIView {

@IBOutlet var productTitle: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var productImage: UIImageView!
@IBOutlet var productDescriptionLabel: UILabel!
@IBOutlet var collectionView: UICollectionView!

}

class TagCollectionViewCell: UICollectionViewCell {

@IBOutlet var tagName: UILabel!

}

Также я добавил немного кода, как показано ниже. Но не имеет смысла! Где моя ошибка?

extension ProductVC : UICollectionViewDelegate , UICollectionViewDataSource {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    var cell: TagCollectionViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell

    if cell == nil {
        collectionView.register(UINib(nibName: "TagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagCollectionViewCell")
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell
    }

    cell.tagName.text = "aa"

    return cell
}

}

1 Ответ

0 голосов
/ 05 июля 2018

Вы не соответствовали протоколам делегата и источника данных. Я думаю в этом проблема. Поместите ниже строки после collection.register

collection.delegate = self
collection.dataSource = self

Надеюсь, это сработает.

...