如何在collectionView中的每2行之后添加自定义视图swift

时间:2019-01-02 08:10:25

标签: ios swift uicollectionview

我正在viewController中实现常规的collectionView来填充数据,并且collection视图有2列,行数取决于数据,现在我的collectionView看起来像这样。

普通collectionView:

enter image description here

这是我在应用程序中实现的功能,因为您可以看到它是具有n行和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)
    })
}

DataSource方法:

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
        }       
}

1 个答案:

答案 0 :(得分:1)

我的代码应具有解释性。我在viewdidload中设置了一些值,以获得所需的视图。

Please see screenshot

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.
}
*/

}