![](https://i.stack.imgur.com/8n7Bf.png)
Я хочу изменить цвет третьей строки на зеленый, когда эта строка появляется
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
} })
Полный код здесь
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()
}
}