首页 > 解决方案 > 如何在collectionView swift中的每2行之后添加一个自定义视图

问题描述

我在 viewController 中实现通用 collectionView 来填充数据,并且 collection view 有 2 列,行数取决于数据,现在我的 collectionView 看起来像这样。

普通collectionView:

在此处输入图像描述

这是我在我的应用程序中实现的,您可以看到它是一个具有 n 行和 2 列的普通集合视图。但是,我们的要求是

业务需求图片:

在每 2 行之后添加一个自定义视图,它是静态的,带有两个标签和一个按钮......

我不知道这是否可能以及如何实现这一点......在搜索了一段时间后,我了解到我们可以通过使用 DecoratorViews 来做到这一点,但我不知道它们是什么以及如何使用它们......如果任何人对如何实现这种布局有任何想法,请指导我..

变量:

let columnsPerRow = 2
let addAfterRows = 5
var cellToShowWithAdds = 0

功能:

func getCategoryProducts() {

    var id = Int()
    var categoryProductsAPI = ""
    if self.brandId != nil {
        id = self.brandId!
        if self.selectedSubCategoryId != nil {
            categoryProductsAPI = "\(API.CATEGORY_BRAND_FILTER)\(self.selectedSubCategoryId!)\(API.BRAND_ID )\(id)"
        } else {
            categoryProductsAPI = "\(API.CATEGORY_BRAND_FILTER)\(self.categoryId!)\(API.BRAND_ID )\(id)"
        }
    } else {
        if self.selectedSubCategoryId != nil {
            id = self.selectedSubCategoryId!
        } else {
            id  = self.categoryId!
        }
        categoryProductsAPI = "\(API.CATEGORY_PRODUCTS)\(id)"
    }
    print(categoryProductsAPI)
    self.cellToShowWithAdds = 0
    self.categoryProductsData = []
    self.loadingView.isHidden = false
    self.loadingActivityIndicator.animate()
    ServiceManager.callGetAPI(url: categoryProductsAPI, view: self, closure: { response in
        self.loadingView.isHidden = true
        self.loadingActivityIndicator.stopAnimating()
        guard let categoryData = response?.result.value  else {return}
        if let categories = categoryData as? [[String : Any]] {
            for product in categories {
                let productName = product["product_name"] as! String
                let productId = product["product_id"] as! String
                let productBrand = product["product_brand"] as! String
                guard let productOffPercent = product["product_sale_of"] else { return }
                let productImage = product["product_image"] as! String
                let productPrice = product["product_price"] as! String
                let productSepcialPrice = product["product_special_price"] as! String
                var newProductPrice = String()
                if productSepcialPrice == "Rs.0.00" {
                    newProductPrice = productPrice
                } else {
                    newProductPrice = productSepcialPrice
                }

                self.categoryProductsData.append(ProductDetails(productID: productId, productName: productName, productPrice: productPrice, productSpecialPrice: newProductPrice, productOff: productOffPercent, productBrand: productBrand, productImageURL: productImage))
            }
            let quot = (self.categoryProductsData.count/(self.columnsPerRow * self.addAfterRows))
            self.cellToShowWithAdds = self.categoryProductsData.count + quot + 1
            DispatchQueue.main.async {
                self.categoryProductsCollection.reloadData()
            }
        }
    }, errorAction: {
        self.loadingView.isHidden = true
        self.loadingActivityIndicator.stopAnimating()
    }, okAction: {
        self.view.setNeedsLayout()
        self.viewWillAppear(true)
    })
}

数据源方法:

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

    return cellToShowWithAdds        
}

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

   if indexPath.row % 5 != 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductDisplayCell
            let productId = Int(categoryProductsData[indexPath.item].productID)
            cell.tag = productId!
            if categoryProductsData[indexPath.item].productImageURL != "" {
                if let productImage = URL(string: categoryProductsData[indexPath.item].productImageURL) {
                    cell.productImage.getImageWith(imageUrl: productImage)
                }
            } else {
                cell.productImage.image = nil
            }
            cell.productNameLabel.text = categoryProductsData[indexPath.item].productName
            cell.sellerNameLabel.text = categoryProductsData[indexPath.item].productBrand
            cell.offerPercentLabel.text = "\(categoryProductsData[indexPath.item].productOff)% Off"

            if "\(categoryProductsData[indexPath.item].productOff)" == "" || "\(categoryProductsData[indexPath.item].productOff)" == "100" || "\(categoryProductsData[indexPath.item].productOff)" == "0" {
                cell.offerPercentLabel.isHidden = true
            } else {
                cell.offerPercentLabel.isHidden = false
            }

            if categoryProductsData[indexPath.item].productSpecialPrice != "Rs.0.00" {
                if categoryProductsData[indexPath.item].productPrice == categoryProductsData[indexPath.item].productSpecialPrice  {
                    cell.originalPriceLable.isHidden = true
                    cell.offerPriceLabel.isHidden = false
                } else {
                    cell.originalPriceLable.isHidden = false
                    cell.offerPriceLabel.isHidden = false
                }
            } else if categoryProductsData[indexPath.item].productSpecialPrice == "Rs.0.00" {
                cell.originalPriceLable.isHidden = true
                cell.offerPriceLabel.isHidden = true
            } else {
                cell.originalPriceLable.isHidden = false
                cell.offerPriceLabel.isHidden = false
            }
            cell.originalPriceLable.attributedText = categoryProductsData[indexPath.item].productPrice.strikeThrough()
            cell.offerPriceLabel.text = categoryProductsData[indexPath.item].productSpecialPrice
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "formCollectionCell", for: indexPath) as! PostRequirementCellCollectionViewCell
            return cell
        }       
}

标签: iosswiftuicollectionview

解决方案


我的代码应该是解释性的。我在 viewdidload 中设置了一些值以获得您需要的视图类型。

请看截图

import UIKit

class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var collectionView : UICollectionView!

let totalProducts = 21
let columnsPerRow = 2
let addAfterRows = 2

var celltoShowWithAds = 0

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    let quot = (totalProducts/(columnsPerRow * addAfterRows))
    print(quot)
    celltoShowWithAds = totalProducts + quot + 1

    collectionView.register(UINib(nibName: "CollectionItemCell", bundle: nil), forCellWithReuseIdentifier: "CollectionItemCell")

    collectionView.register(UINib(nibName: "CollectionAdvertisementCell", bundle: nil), forCellWithReuseIdentifier: "CollectionAdvertisementCell")

    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.reloadData()
    //collectionView.backgroundColor = UIColor.blue
}

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

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.row == 0{
        let myCell:CollectionAdvertisementCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionAdvertisementCell", for: indexPath) as! CollectionAdvertisementCell
        return myCell as CollectionAdvertisementCell;

    }else if indexPath.row % 5 == 0{
        let myCell:CollectionAdvertisementCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionAdvertisementCell", for: indexPath) as! CollectionAdvertisementCell

        return myCell as CollectionAdvertisementCell;
    }else{
        let myCell:CollectionItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionItemCell", for: indexPath) as! CollectionItemCell

        return myCell as CollectionItemCell;
    }



}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if indexPath.row == 0{
        return CGSize(width: view.frame.width, height: 0.0)
    }else if indexPath.row % 5 == 0 {
        return CGSize(width: view.frame.width, height: 80.0)
    }else{
        return CGSize(width: view.frame.width/CGFloat(columnsPerRow), height: 200.0)
    }

}




//Use for interspacing
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout
    collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
}
*/

}

推荐阅读