简体   繁体   English

如何在集合视图 swift 5 中更改动态行的颜色

[英]How to change color of dynamic row in collection-view swift 5

I want to change color of third row to green when this row occurs当第三行出现时,我想将第三行的颜色更改为绿色

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseID, for: indexPath) as? CollectionViewCell else {
            return UICollectionViewCell()
        }


        cell.titleLabel.text = data[indexPath.section][indexPath.row]


      filteredReportData?.forEach({
            let marketTotal = $0.isTotal
        if( marketTotal == true && indexPath.section % 8 == 1   ) {
                cell.backgroundColor = AppConstants.COLOR_APP_GREEN
                cell.titleLabel.textColor = .white            }
         else {
                 cell.backgroundColor = gridLayout.isItemSticky(at: indexPath)   ? AppConstants.COLOR_APP_GREEN : .white
                 cell.titleLabel.textColor = gridLayout.isItemSticky(at: indexPath) ? .white : .black

        } })

Complete code here完整代码在这里

class GPStatusReportVC: UIViewController {

    @IBOutlet weak var lblDatetime : UILabel!
    private var markets = [GPMarket]()
    private var sDs = [SD]()
    private var selectionType = 1
    private var selectedMarketID = "0"
    private var selectedSD = ""

    private var data = [[String]]()
    let firstRow = ["Market","Location",
                    "GP Ach (%)","GP Goals ($)", "GP With Spiff ($)",
                    "Daily Opps Goal", "Opps Ach","GA Goals", "GA Ach", "UPG Ach",
                    "BP Count", "AP Count", "APO Ach", "Acc GP ($)"]

    @IBOutlet weak var txtSearch : UITextField!
    @IBOutlet weak var btnSearch : UIButton!
    @IBOutlet weak var btnReset : UIButton!
    @IBOutlet weak var segmentedControl : UISegmentedControl!
    var myPickerView : UIPickerView!

    var reportData: GPStatusReportAPIModel? {
        didSet{
            if let reportData = reportData {
                data.removeAll()
                filteredReportData = reportData.data

                self.markets = reportData.market
                self.sDs = reportData.sd
                self.lblDatetime.text = reportData.dateTimess[0].timeStamp
            }
        }
    }

    var filteredReportData : [GPData]? {
        didSet {
            if let reportData = filteredReportData {
                if reportData.count > 0 {
                    data.removeAll()

                    var secondRow = ["","Grand Total","","", "", "", "", "", "", "", "", "", "", ""]
                    if let total = self.reportData?.totalData[0] {
                        secondRow = ["", "Grand Total", "\(total.gpPerAchieved)", "\(total.totalGPGOALS)", "\(total.totalAchievedGPWithSpiff)", "\(total.totalOPPSGoal)", "\(total.oppsAchieved)",
                            "\(total.gaGoal)", "\(total.gaAchieved)", "\(total.achievedUpgradeEquipment)",
                            "\(total.billPayCount)", "\(total.autoPayCount)", "\(total.apoArchived)", "\(total.accessoriesGP)"]
                    }

                    data.append(firstRow)
                    data.append(secondRow)
                        reportData.forEach({

                            let marketWiseTotal = $0.isTotal

                            if (marketWiseTotal == true){
                                    let thirdrow = [$0.market, "TOTAL", $0.gpPerAchieved, $0.totalGPGOALS, $0.totalAchievedGPWithSpiff, $0.totalOPPSGoal, $0.oppsAchieved, $0.gaGoal, $0.gaAchieved, $0.achievedUpgradeEquipment, $0.billPayCount, $0.autoPayCount, $0.apoArchived, $0.accessoriesGP]
                                    let fifthrow = ["","","","","","","","","","","","","",""]
                                    data.append((thirdrow as? [String] ?? [""]))
                                    data.append((fifthrow))
                            } else {
                                if(marketWiseTotal == false) {
                                let fourthrow = [$0.market, $0.location, $0.gpPerAchieved, $0.totalGPGOALS, $0.totalAchievedGPWithSpiff, $0.totalOPPSGoal, $0.oppsAchieved, $0.gaGoal, $0.gaAchieved, $0.achievedUpgradeEquipment, $0.billPayCount, $0.autoPayCount, $0.apoArchived, $0.accessoriesGP]
                                    data.append(fourthrow as? [String] ?? [""])

                                } }
                                })
                    //setupDataSizes()

                    DispatchQueue.main.async {
                        self.gridCollectionView.reloadData()
                    }
                    self.view.layoutIfNeeded()
                }
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.txtSearch.delegate = self
        self.rotateToLandsScapeDevice()
        self.navigationItem.title = "GP Status Report"
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

        btnSearch.layer.cornerRadius = btnSearch.frame.height/2
        btnSearch.clipsToBounds = true

        btnReset.layer.cornerRadius = btnSearch.frame.height/2
        btnReset.clipsToBounds = true

        fetchGPStatusReport()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.rotateToPotraitScapeDevice()
    }

    func rotateToLandsScapeDevice(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.myOrientation = .landscapeLeft
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
        UIView.setAnimationsEnabled(true)
    }

    func rotateToPotraitScapeDevice(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.myOrientation = .portrait
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        UIView.setAnimationsEnabled(true)
    }

    @IBAction func segmentedIndexChanged(_ sender : UISegmentedControl) {
        txtSearch.text = ""
        txtSearch.resignFirstResponder()
        self.selectedMarketID = "0"
        self.selectedSD = ""

        if sender.selectedSegmentIndex == 0 {
            self.selectionType = 1
        } else {
            self.selectionType = 2
        }
    }

    @IBAction func resetFilter(_ sender : UIButton) {
        txtSearch.text = ""
        self.selectedMarketID = "0"
        self.selectedSD = ""
        //self.filteredReportData = reportData?.data
        self.filteredReportData?.removeAll()
        fetchGPStatusReport()
    }

    @IBOutlet weak var gridCollectionView: UICollectionView! {
        didSet {
            gridCollectionView.bounces = false
        }
    }

    @IBOutlet weak var gridLayout: StickyGridCollectionViewLayout! {
        didSet {
            gridLayout.stickyRowsCount = 2
            gridLayout.stickyColumnsCount = 2
        }
    }

    func fetchGPStatusReport() {
        APIClient.fetchGPStatusReport().execute(onSuccess: { (response) in
            printLog(message: "REPORT DATA FETCHED")
            self.reportData = response
        }) { (error) in
            printLog(message: "FAILED TO FETCH Status Count REPORT = \(error.localizedDescription)")
            self.showAPIErrorAlert(okClick: {
                self.fetchGPStatusReport()
            }, cancelClick: {})
        }
    }

    func fetchGPStatusReportByFilter(filterBy: String, filterConstant: String) {
        APIClient.fetchGPStatusReportByFilter(filterBy: filterBy.replacingOccurrences(of: " ", with: "%60"), filterConstant: filterConstant).execute(onSuccess: { (response) in
            printLog(message: "REPORT DATA FETCHED")
            self.reportData = response
        }) { (error) in
            printLog(message: "FAILED TO FETCH GP REPORT = \(error.localizedDescription)")
            self.showAPIErrorAlert(okClick: {
                self.fetchGPStatusReportByFilter(filterBy: filterBy, filterConstant: filterConstant)
            }, cancelClick: {})
        }
    }

}
// MARK: - Collection view data source and delegate methods

extension GPStatusReportVC: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data.count
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseID, for: indexPath) as? CollectionViewCell else {
            return UICollectionViewCell()
        }


        cell.titleLabel.text = data[indexPath.section][indexPath.row]


      filteredReportData?.forEach({
            let marketTotal = $0.isTotal
        if( marketTotal == true && indexPath.section % 8 == 1   ) {
                cell.backgroundColor = AppConstants.COLOR_APP_GREEN
                cell.titleLabel.textColor = .white            }
         else {
                 cell.backgroundColor = gridLayout.isItemSticky(at: indexPath)   ? AppConstants.COLOR_APP_GREEN : .white
                 cell.titleLabel.textColor = gridLayout.isItemSticky(at: indexPath) ? .white : .black

        } })
            //  cell.backgroundColor = gridLayout.isItemSticky(at: indexPath)   ? AppConstants.COLOR_APP_GREEN : .white
           //  cell.titleLabel.textColor = gridLayout.isItemSticky(at: indexPath) ? .white : .black



        if indexPath.section == 1 {
            if indexPath.row > 6 {
                cell.contentView.layer.borderWidth = 0.5
            } else {
               cell.contentView.layer.borderWidth = 0.0
            }
        } else {
            cell.contentView.layer.borderWidth = 0.5
        }

        if indexPath.row < 2 && indexPath.section > 1 {
            cell.titleLabel.textAlignment = .left
        } else {
            cell.titleLabel.textAlignment = .center
        }

        return cell
    }
}

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

        if indexPath.row < 2 {
           return CGSize(width: 100, height: 36)
        }

        return CGSize(width: 90, height: 36)
    }
}

extension GPStatusReportVC: UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    func pickUp(_ textField : UITextField){
        self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
        self.myPickerView.delegate = self
        self.myPickerView.dataSource = self
        self.myPickerView.backgroundColor = UIColor.white
        textField.inputView = self.myPickerView

        // ToolBar
        let toolBar = UIToolbar()
        toolBar.barStyle = .default
        toolBar.isTranslucent = true
        toolBar.tintColor = AppConstants.COLOR_APP_GREEN //UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
        toolBar.sizeToFit()

        // Adding Button ToolBar
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneClick))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClick))
        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        textField.inputAccessoryView = toolBar

    }
    //MARK:- PickerView Delegate & DataSource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if self.selectionType == 2 {
            return sDs.count
        } else {
            return markets.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if self.selectionType == 2 {
            return sDs[row].sdName
        } else {
            return markets[row].markName
        }
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var pickerLabel = view as! UILabel?
        if view == nil {
            pickerLabel = UILabel()
            pickerLabel?.numberOfLines = 0
            // let hue = CGFloat(row)/CGFloat(markets.count)
            // pickerLabel?.backgroundColor = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
        }
        var titleText = ""

        if self.selectionType == 2 {
            titleText = sDs[row].sdName
        } else {
            titleText = markets[row].markName
        }

        let myTitle = NSAttributedString(string: titleText, attributes: [NSAttributedString.Key.font:UIFont(name: "Georgia", size: 20.0)!,NSAttributedString.Key.foregroundColor:UIColor.black])
        pickerLabel!.attributedText = myTitle
        pickerLabel!.textAlignment = .center

        return pickerLabel!

    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 54.0
    }

    //MARK:- TextFiled Delegate
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if self.selectionType == 2 {
            if self.sDs.count > 0 {
                self.pickUp(textField)
            } else {
                self.showAlertDialogue(message: "No SD Found")
            }
        } else {
            if self.markets.count > 0 {
                self.selectionType = 1
                self.pickUp(textField)
            } else {
                self.showAlertDialogue(message: "No Market Found")
            }
        }
    }
    //MARK:- Button
    @objc func doneClick() {
        let selectedIndex = myPickerView.selectedRow(inComponent: 0)
        if self.selectionType == 2 {
            txtSearch.text = "\(sDs[selectedIndex].sdName)"
            self.selectedSD = "\(sDs[selectedIndex].sdName)"
            txtSearch.resignFirstResponder()

            filteredReportData?.removeAll()
            //self.filteredReportData = self.reportData?.data.filter({ $0.SD == self.selectedSD })

            self.fetchGPStatusReportByFilter(filterBy: self.selectedSD , filterConstant: "SD")

        } else {
            txtSearch.text = "\(markets[selectedIndex].markName)"
            self.selectedMarketID = "\(markets[selectedIndex].markID)"
            txtSearch.resignFirstResponder()

            filteredReportData?.removeAll()
            //self.filteredReportData = self.reportData?.data.filter({ $0.market == "\(markets[selectedIndex].markName)"})

            self.fetchGPStatusReportByFilter(filterBy: txtSearch.text ?? " " , filterConstant: "M")
        }
    }
    @objc func cancelClick() {
        txtSearch.resignFirstResponder()
    }
}

Don't loop the filteredReportData array in cellForItemAt , get the the current item from filteredReportData using indexpath like,不要在cellForItemAt 中循环过滤报告数据数组,使用索引路径从过滤报告数据中获取当前项目,例如,

filteredReportData[indexPath.row]过滤报告数据[indexPath.row]

then do your calculation and set the cell background color, Don't forgot to add layoutIfNeeded() before return the cell然后进行计算并设置单元格背景颜色,在返回单元格之前不要忘记添加layoutIfNeeded()

let marketTotal = filteredReportData[IndexPath.row].isTotal
    if( marketTotal == true && indexPath.section % 8 == 1   ) {
            cell.backgroundColor = AppConstants.COLOR_APP_GREEN
            cell.titleLabel.textColor = .white            }
     else {
             cell.backgroundColor = gridLayout.isItemSticky(at: indexPath)   ? AppConstants.COLOR_APP_GREEN : .white
             cell.titleLabel.textColor = gridLayout.isItemSticky(at: indexPath) ? .white : .black
    }
    view.layoutIfNeeded()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何显示库中的实时照片视频并在iOS Swift的收藏夹视图中显示? - How to display Live-photos Videos from library and display in Collection-View in iOS Swift? 如何在Swift iOS中更改自定义“收藏夹视图”单元格的背景颜色? - How to change the background color of a custom Collection View cell in swift iOS? 集合视图中有多个Tableview - Multiple Tableviews inside Collection-view UICollectionViewCell相对于其集合视图的大小 - UICollectionViewCell sized relative to its collection-view 如何在集合视图中更改视图的颜色 - How to change the color of View in collection view 如何实现小视图变成全屏视图的效果? 类似于 Snapchat 从集合视图到内容视图的转换 - How to achieve effect where small view becomes full screen view? Similar to Snapchat transition from collection-view to content view 如何获取集合视图动态行数? - How to get Collection view Dynamic Row count? 如何快速动态更改集合视图的大小? - How to dynamically change size of collection view in swift? 如何在 swift %@ 中更改部分动态字符串的颜色? - How to change color of part of dynamic string in swift %@? 如何快速更改集合视图的高度 - How to change the height of the collection view in swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM