ios - 如果计数等于 0,如何将显示数据从 API 跳过到 Collection View 单元格

标签 ios swift

我正在将 API 中的数据解析到 Collection View 中,其中有一个名为 count 的字段。我不想显示 count 为 0 的数据,并且希望其他 Collection View 单元格相应地重新排列。

Assets 文件夹的屏幕截图: screenshot of assets folder

我的结果截图 result of my app when it starts

到目前为止,这是我的代码:

import UIKit

class CategoryViewController: UIViewController {


//MARK: IBOutlets
@IBOutlet weak var store_bar: UIViewX!
@IBOutlet weak var store_title: UIButton!
@IBOutlet weak var category_title: UIButton!
@IBOutlet weak var category_bar: UIViewX!
@IBOutlet weak var categoryColView: UICollectionView!

var selectedBtnIndex:Int = 1

var categoryData = [ModelCategories]()
var storeData = [ModelStore]()

override func viewDidLoad() {
    super.viewDidLoad()

    // register collectionview cell
    self.categoryColView.register(UINib(nibName: "CategoryCell1", bundle: nil), forCellWithReuseIdentifier: "CategoryCell1")
    self.categoryColView.register(UINib(nibName: "StoresCell", bundle: nil), forCellWithReuseIdentifier: "StoresCell")

    self.store_bar.isHidden = true

    self.getCategoriesList()
    self.getStoreList()

}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

@objc func click_Category(sender: UIButton!) {
    UIView.animate(withDuration: 1.0) {
        sender.isSelected = !sender.isSelected
    }
}

@objc func click_store(sender: UIButton!) {
    UIView.animate(withDuration: 1.0) {
        sender.isSelected = !sender.isSelected
    }
}


//MARK: IBActions

@IBAction func categoriesData(_ sender: UIButton) {

    selectedBtnIndex = 1
    self.categoryColView.isHidden = false
    self.store_bar.isHidden = true
    self.category_title.setTitleColor(UIColor.black, for: .normal)
    self.category_bar.isHidden = false
    self.store_title.setTitleColor(UIColor(rgb: 0xAAAAAA), for: .normal)
    self.categoryColView.reloadData()

}

@IBAction func storeData(_ sender: UIButton) {

    selectedBtnIndex = 2
    self.categoryColView.isHidden = false
    self.store_bar.isHidden = false
    self.store_title.setTitleColor(UIColor.black, for: .normal)
    self.category_bar.isHidden = true
    self.category_title.setTitleColor(UIColor(rgb: 0xAAAAAA), for: .normal)
    self.categoryColView.reloadData()
}

@IBAction func showHomeScreen(_ sender: UIButton) {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
    self.navigationController?.pushViewController(vc, animated:true)
}

@IBAction func toSearchPage(_ sender: UIButton) {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "SearchPageController") as! SearchPageController
    self.navigationController?.pushViewController(vc, animated:true)
}

func getCategoriesList() {
    if ApiUtillity.sharedInstance.isReachable() {
        ApiUtillity.sharedInstance.StartProgress(view: self.view)
        APIClient<ModelBaseCategoryList>().API_GET(Url: SD_GET_CategoriesList, Params: [:], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

            ApiUtillity.sharedInstance.StopProgress(view: self.view)

            if(modelResponse.success == true) {

                self.categoryData.removeAll()
                let resul_array_tmp_new = modelResponse.categories! as NSArray

                if resul_array_tmp_new.count > 0 {
                    for i in modelResponse.categories! {
                        self.categoryData.append(i)
                    }
                }
            }
            else {
                self.view.makeToast(modelResponse.message)
            }
            ApiUtillity.sharedInstance.StopProgress(view: self.view)
            self.categoryColView.reloadData()
        }) { (failed) in
            ApiUtillity.sharedInstance.StopProgress(view: self.view)
            self.view.makeToast(failed.localizedDescription)
        }
    }
    else
    {
        self.view.makeToast("No Internet Connection..")
    }
}

func getStoreList() {
    if ApiUtillity.sharedInstance.isReachable() {
        ApiUtillity.sharedInstance.StartProgress(view: self.view)
        APIClient<ModelBaseStoreList>().API_GET(Url: SD_GET_StoreList, Params: [:], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

            ApiUtillity.sharedInstance.StopProgress(view: self.view)

            if(modelResponse.success == true) {

                self.storeData.removeAll()
                let resul_array_tmp_new = modelResponse.store! as NSArray

                if resul_array_tmp_new.count > 0 {
                    for i in modelResponse.store! {
                        self.storeData.append(i)
                    }
                }
            }
            else {
                self.view.makeToast(modelResponse.message)
            }
            ApiUtillity.sharedInstance.StopProgress(view: self.view)
            self.categoryColView.reloadData()
        }) { (failed) in
            ApiUtillity.sharedInstance.StopProgress(view: self.view)
            self.view.makeToast(failed.localizedDescription)
        }
    }
    else
    {
        self.view.makeToast("No Internet Connection..")
    }
}
}


    //MARK: Delegate and Data Source Methods
    extension CategoryViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {



func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if selectedBtnIndex == 1{
        return categoryData.count
    }else {
        return storeData.count
    }
}

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

    if selectedBtnIndex == 1{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell1", for: indexPath) as! CategoryCell1

        let dict = categoryData[indexPath.row]

        if let catName = dict.name, catName.count != 0 {
            cell.categoryName.text = catName
        }

        if let catOffersCount = dict.count {
            if catOffersCount <= 1 {
                cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offer"
                cell.categoryImage.image = UIImage(named: "tickets")
            }else {
                cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offers"
            }
        }

        if dict.slug == "mens" {
            cell.categoryImage.image = UIImage(named: "MENS")
        } else if dict.slug == "electronics" {
            cell.categoryImage.image = UIImage(named: "ELECTRONICS")
        }else if dict.slug == "beauty" {
            cell.categoryImage.image = UIImage(named: "BEAUTY")
        }else if dict.slug == "fashion" {
            cell.categoryImage.image = UIImage(named: "FASHION")
        }else if dict.slug == "kids-clothing" {
            cell.categoryImage.image = UIImage(named: "KIDS FASHION")
        }else if dict.slug == "travel" {
            cell.categoryImage.image = UIImage(named: "TRAVEL")
        }else if dict.slug == "womens-apparels" {
            cell.categoryImage.image = UIImage(named: "WOMENS APPARELS")
        }else if dict.slug == "eyewear" {
            cell.categoryImage.image = UIImage(named: "EYEWEAR")
        }else {
            cell.categoryImage.image = UIImage(named: "tickets")
        }


        cell.btn_click.tag = indexPath.row
        cell.btn_click.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)
        cell.btn_click.setImage(#imageLiteral(resourceName: "image_checked"), for: .selected)
        cell.btn_click.addTarget(self, action: #selector(self.click_Category), for: .touchUpInside)
        return cell
    }else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StoresCell", for: indexPath) as! StoresCell

        let dict = storeData[indexPath.row]

        if let storeName = dict.name, storeName.count != 0 {
            cell.storeName.text = storeName
        }

        if let storeOfferCount = dict.count {
            cell.storeOfferCount.text = "\(storeOfferCount)"+" "+"Offers"
        }

        cell.store_btn_click.tag = indexPath.row
        cell.store_btn_click.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)
        cell.store_btn_click.setImage(#imageLiteral(resourceName: "image_checked"), for: .selected)
        cell.store_btn_click.addTarget(self, action: #selector(self.click_store), for: .touchUpInside)
        return cell
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if selectedBtnIndex == 1{
       return CGSize(width: (UIScreen.main.bounds.width) / 3, height: 93)
    }else {
        return CGSize(width: (UIScreen.main.bounds.width) / 3, height: 93)
    }
}

最佳答案

我认为你应该在这样的响应方法中添加一个条件,以消除 count 属性等于 0 的数据。

if resul_array_tmp_new.count > 0 {
    for i in modelResponse.store! {
        if i.count != 0 {
            self.storeData.append(i)
        }
    }
}

类别列表相同。

if resul_array_tmp_new.count > 0 {
    for i in modelResponse.categories! {
        if i.count != 0 {
            self.categoryData.append(i)
        }
    }
}

关于ios - 如果计数等于 0,如何将显示数据从 API 跳过到 Collection View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56636022/

相关文章:

iOS 企业 APNs 证书过期

ios - 如何重新创建 UITableViewController 的初始化行为?

ios - 与 NSUserDefaults 的表情符号比较错误

ios - 使用 AVCaptureMovieFileOutput 开始/停止录制视频时,播放与设备相机应用程序中听到的相同的声音吗?

swift 3 : Tableview select row goes to different navigation views

可以重新声明 Swift 内置协议(protocol)吗?为什么?

ios - 启动图像不显示

ios - 创建具有透明背景 Swift 的模态视图

swift - openURL() 中的双标签会使应用程序崩溃

ios - 当管理员从 Firebase 手动删除他时如何通知用户?