Ios 如何更改集合视图swift 5中动态行的颜色
当这一行出现时,我想将第三行的颜色更改为绿色Ios 如何更改集合视图swift 5中动态行的颜色,ios,swift,xcode,Ios,Swift,Xcode,当这一行出现时,我想将第三行的颜色更改为绿色 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.reuseI
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()
}
}
类GPStatusReportVC:UIViewController{
@IBVAR lblDatetime:UILabel!
私人var市场=[GPMarket]()
私有变量sDs=[SD]()
私有变量selectionType=1
私有变量selectedMarketID=“0”
private var selectedSD=“”
私有变量数据=[[String]]()
让第一行=[“市场”,“位置”,
“GP Ach(%)”、“GP目标($)”、“具有Spiff的GP($)”,
“每日Opps目标”、“Opps Ach”、“GA目标”、“GA Ach”、“UPG Ach”,
“BP计数”、“AP计数”、“APO Ach”、“Acc GP($)”]
@IBMOutlet弱var txtSearch:UITextField!
@IBOutlet弱var BTN搜索:UIButton!
@IBOutlet弱var btnReset:UIButton!
@IBOutlet弱var分段控制:UISegmentedControl!
var myPickerView:UIPickerView!
var reportData:GPStatusReportAPIModel{
迪塞特{
如果let reportData=reportData{
data.removeAll()
filteredReportData=reportData.data
self.markets=reportData.market
self.sDs=reportData.sd
self.lblDatetime.text=reportData.DateTimes[0]。时间戳
}
}
}
var filteredReportData:[GPData]{
迪塞特{
如果let reportData=filteredReportData{
如果reportData.count>0{
data.removeAll()
var secondRow=[“”、“总计”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”、“”]
如果let total=self.reportData?.totalData[0]{
第二行=[“”,“,”总计“,“\(Total.gpperacheed)”,“\(Total.totalGPGOALS)”,“\(Total.totalAcacheedPWithSpiff)”,“\(Total.totalOPPSGoal)”,“\(Total.Oppsacheed)”,
“\(total.gaGoal)”,“\(total.gaacheed)”,“\(total.acheedUpgradeEquipment)”,
“\(total.billPayCount)”、“\(total.autoPayCount)”、“\(total.apoArchived)”、“\(total.accessoriesGP)”]
}
data.append(第一行)
data.append(第二行)
reportData.forEach({
let marketWiseTotal=$0.0总计
如果(marketWiseTotal==真){
让thirdrow=[$0.market,“TOTAL”、$0.gpperacheed、$0.totalGPGOALS、$0.totalAchievedPwithSpiff、$0.totalOPPSGoal、$0.oppsHieved、$0.gaGoal、$0.gaAchieved、$0.AchievedUpgradeDevice、$0.billPayCount、$0.autoPayCount、$0.apocated、$0.Accessories]
让FIFTROW=[,,,,,,,,,,,,,,,,,,,,,,,]
data.append((thirdrow为?[String]??[“”]))
data.append((fiftrow))
}否则{
如果(marketWiseTotal==false){
让fourthrow=[$0.market,$0.location,$0.gpperacheed,$0.totalGPGOALS,$0.totalOPPSGoal,$0.oppsacheed,$0.gaGoal,$0.gaacheed,$0.acheedUpgradeDevice,$0.billPayCount,$0.autoPayCount,$0.apocated,$0.accessories]
data.append(fourthrow为?[String]??[“”])
} }
})
//setupDataSizes()
DispatchQueue.main.async{
self.gridCollectionView.reloadData()
}
self.view.layoutifneed()
}
}
}
}
重写func viewDidLoad(){
super.viewDidLoad()
self.txtSearch.delegate=self
self.rotateTolandscapeDevice()的
self.navigationItem.title=“GP状态报告”
}
覆盖函数视图将出现(uo动画:Bool){
super.viewwillbeen(true)
btnSearch.layer.cornerRadius=btnSearch.frame.height/2
btnSearch.clipstobunds=true
btnReset.layer.cornerRadius=btnSearch.frame.height/2
btnReset.clipstobunds=true
fetchGPStatusReport()
}
覆盖函数视图将消失(u动画:Bool){
超级。视图将消失(动画)
自旋转PotraitScapeDevice()
}
func RotateTolandsCapeDevice(){
让appDelegate=UIApplication.shared.delegate为!appDelegate
appDelegate.myOrientation=.landscapeLeft
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue,forKey:“方向”)
UIView.SetAnimationEnabled(真)
}
func rotateToPotraitScapeDevice(){
让appDelegate=UIApplication.shared.delegate为!appDelegate
appDelegate.myOrientation=.portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue,forKey:“方向”)
UIView.SetAnimationEnabled(真)
}
@iAction func segmentedIndexChanged(\发送方:UISegmentedControl){
txtSearch.text=“”
txtSearch.resignFirstResponder()辞职
self.selectedMarketID=“0”
self.selectedSD=“”
如果sender.selectedSegmentIndex==0{
self.selectionType=1
}否则{
self.selectionType=2
}
}
@iAction func resetFilter(\发送方:UIButton){
txtSearch.text=“”
self.selectedMarketID=“0”
self.selectedSD=“”
//self.filteredReportData=reportData?.data
self.filteredReportData?.removeAll()
fetchGPStatusReport()
}
@ibvar gridCollectionView:UICollectionView{
迪塞特{
gridCollectionView.bounces=false
}
}
@IBVar gridLayout:StickyGridCollectionViewLayout{
迪塞特{
gridLayout.stickyRowsCount=2
gridLayout.StickyColumnsko
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()