【问题标题】:Reach CollectionViewCell into Xib with Programatically以编程方式达到 Xib 宽度的 UICollectionViewCell
【发布时间】:2018-07-05 14:34:52
【问题描述】:

我创建了一个 Xib 文件并调用 ViewController。我还在 Xib 文件中创建了一个 CollectionView。现在我想访问 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
}

}

【问题讨论】:

  • collectionView.register 应该在 viewdidload 中完成

标签: ios swift xcode uicollectionviewcell xib


【解决方案1】:

您不符合委托和数据源协议。我认为这是问题所在。在 collection.register

之后添加以下行
collection.delegate = self
collection.dataSource = self

希望这会奏效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多