美文网首页
CollectionViewDemo (Swift xib)

CollectionViewDemo (Swift xib)

作者: 不要虚度美好的时光 | 来源:发表于2022-04-27 21:57 被阅读0次

    ios-swift-uicollectionviewcell-from-xib
    通过 xib 创建自定义 UICollectionViewCell

    image.png
        @IBOutlet weak var collectionView: UICollectionView!
        let productCollectionViewCellId = "ProductCollectionViewCell"
        var products = [ProductDto]()
    
        // register cell
        let nibCell = UINib(nibName: productCollectionViewCellId, bundle: nil)
        collectionView.register(nibCell, forCellWithReuseIdentifier: productCollectionViewCellId)
    
        // init data
        for _ in 1...25 {
            let product = ProductDto()
            product?.name = "Wireless Headphone"
            product?.desc = "Hear the music, Not the noise ;)"
            products.append(product!)
        }
        collectionView.reloadData()
    
    extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
        
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
        
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return products.count
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            let inset:CGFloat = 10
            return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: UIScreen.main.bounds.width, height: 80)
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: productCollectionViewCellId, for: indexPath) as! ProductCollectionViewCell
            let product = products[indexPath.row]
            cell.img.image = UIImage(named: "img_product")
            cell.lbName.text = product.name!
            cell.lbDesc.text = product.desc!
            
            return cell
        }
        
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let product = products[indexPath.row]
            print("\(indexPath.row) - \(product.name!)")
        }
    }
    

    相关文章

      网友评论

          本文标题:CollectionViewDemo (Swift xib)

          本文链接:https://www.haomeiwen.com/subject/mjalyrtx.html