Adding an ad after every 5 cells in tableview is replacing content - ios

I've search on stackoverflow for a hint on how to do that and I found this question here but that did not solved my problem, I want the same thing( add an advertise after every 5 rows), and I tried the solution mentioned there, but what I'm getting is the first row is being replaced by the ad, as the 5th, and so on, my normal content is being replaced by the ad.
So I want to achieve this:
row 0 = normal content
row 1 = normal content
row 2 = normal content
row 3 = normal content
row 4 = normal content
row 5 = ad
row 6 = normal content
...
here is what I tried:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row % 5 == 0 && indexPath.row != 0) {
if let cellBanner = tableView.dequeueReusableCell(withIdentifier: "cellBanner", for: indexPath) as? BannerCell {
return cellBanner
} else {
return UITableViewCell()
}
} else {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? AnuncioCell {
if AnunciosService.instance.anuncios.count >= indexPath.row {
let anuncio = AnunciosService.instance.anuncios[indexPath.row]
let rowsToLoadFromBottom = 5;
let rowsLoaded = AnunciosService.instance.anuncios.count
if (!self.fetchingMore && (indexPath.row - (indexPath.row / 5) >= (rowsLoaded - rowsToLoadFromBottom))) {
let totalRows = AnunciosService.instance.anunciosCount
let remainingAnunciosToLoad = totalRows - rowsLoaded;
if (remainingAnunciosToLoad > 0) {
self.loadMoreAnuncios()
}
}
cell.configureCell(anuncio: anuncio)
let checkValue = Double(anuncio.user.nota)!
if checkValue < 1.0 {
cell.notaView.isHidden = true
}else{
cell.notaView.isHidden = false
}
if anuncio.destaque {
cell.destaque.isHidden = false
} else {
cell.destaque.isHidden = true
}
if anuncio.status == 0 {
if cell.imgAnuncio.image != nil{
Noir(originalImage: cell.imgAnuncio)
}
cell.sold_out.isHidden = false
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false;
} else {
cell.sold_out.isHidden = true
cell.isUserInteractionEnabled = true;
cell.selectionStyle = .default
}
}
return cell
} else {
return UITableViewCell()
}
}
}
numberOfRowsInSection:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if AnunciosService.instance.anuncios.count == 0 {
return 0
}
return AnunciosService.instance.anuncios.count + BannersService.instance.banners.count
}

I was doing it wrong, for those who want to know how I solved it:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row + 1
if (index % 6 == 0 && indexPath.row != 0 && index/6 <= BannersService.instance.banners.count) {
let cellBanner = tableView.dequeueReusableCell(withIdentifier: "cellBanner", for: indexPath) as! BannerCell
return cellBanner
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AnuncioCell
let index = indexPath.row - (indexPath.row / 6)
if AnunciosService.instance.anuncios.count > index {
let anuncio = AnunciosService.instance.anuncios[index]
let rowsToLoadFromBottom = 5;
let rowsLoaded = AnunciosService.instance.anuncios.count
if (!self.fetchingMore && (index >= (rowsLoaded - rowsToLoadFromBottom))) {
let totalRows = AnunciosService.instance.anunciosCount
let remainingAnunciosToLoad = totalRows - rowsLoaded;
if (remainingAnunciosToLoad > 0) {
self.loadMoreAnuncios()
}
}
cell.configureCell(anuncio: anuncio)
let checkValue = Double(anuncio.user.nota)!
if checkValue < 1.0 {
cell.notaView.isHidden = true
}else{
cell.notaView.isHidden = false
}
if anuncio.destaque {
cell.destaque.isHidden = false
} else {
cell.destaque.isHidden = true
}
if anuncio.status == 0 {
if cell.imgAnuncio.image != nil {
Noir(originalImage: cell.imgAnuncio)
}
cell.sold_out.isHidden = false
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false;
} else {
cell.sold_out.isHidden = true
cell.isUserInteractionEnabled = true;
cell.selectionStyle = .default
}
}
return cell
}
}

Related

How to hide UITableview cell and white space after hide it

I'm trying to hide a cell from a UITableView. I know that UITableViewCell has a property called hidden but after hide I don't want white space. I want the boxes to be close together. I just want hide only condition result_id == nil || resuld_id == "" and hide a cell according to the condition
Func cellForRowAt
I already hide cell like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! Static1vs1Cell
let cellNoMatch = tableView.dequeueReusableCell(withIdentifier: reuseNoMatchIdentifier) as! NoMatchTableViewCell
cell.selectionStyle = .none
cellNoMatch.selectionStyle = .none
cellNoMatch.backgroundColor = .clear
if indexPath.section == 0 {
if currentData.count == 0 {
cellNoMatch.historyLabel.text = "No Match"
return cellNoMatch
}
let ad: HistoryListModel = currentData[indexPath.row] as! HistoryListModel
cell.setUI(md: ad, indexPath: indexPath, is_finish: false)
}else if indexPath.section == 1 {
if finishedData.count == 0 {
cellNoMatch.historyLabel.text = "No Match"
return cellNoMatch
}
let ad: HistoryListModel = finishedData[indexPath.row] as! HistoryListModel
cell.setUI(md: ad, indexPath: indexPath, is_finish: true)
if md.result_id == nil || md.result_id == ""{
cell.isHidden = true
}
}
return cell
}
Func heightForRowAt
I set height = 0
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var rowHeight:CGFloat = 50
if currentData.count > 0 {
rowHeight = 95
}
else if finishedData.count > 0 {
let ad: HistoryListModel = finishedData[indexPath.row] as! HistoryListModel
if ad.result_id == nil || ad.result_id == "" {
return 0.0
}
else{
return 95
}
} else if finishedData.count == 0 {
rowHeight = 50
} else if currentData.count == 0 {
rowHeight = 50
}
return rowHeight
}
For example, you need to filter the list of table elements and hide unnecessary.
Create a separate array for filtered items and update the table details.
Use it for table delegates.
NB. This solution requires additional memory, do not use it with a very large number of items.
var fullArray : [String] = [] {
didSet {
setFiltered()
}
}
var filteredArray : [String] = [] {
didSet {
tableView.reloadData() // or use batch update
}
}
let tableView = UITableView()
func setFiltered() {
filteredArray = fullArray.filter({ $0 != "Hidden" })
}

Swift 5 UITableViewCell : Expand one section and collapse the expanded section

I have implemented the following code to add expand/collapse feature to UITableView sections. When user click each section1, it expands and when we click the same section1 it collapses. But, I want the section1 to collapse, if I am expanding section2. How can I implement this feature to my code added below.
struct FaqData{
var faqHead = String()
var faqImage = String()
var questionArray : [(question : String, answer : String, answerurl : String)] = [(String,String,String)]()
var openSection = Bool()
}
var supportArray = [FaqData]()
func numberOfSections(in tableView: UITableView) -> Int {
return supportArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}
else{
if supportArray[section].openSection == true{
return supportArray[section].questionArray.count + 1
}else{
return 1
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportCenterID", for: indexPath) as! SupportCenterTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.faqCollection.reloadData()
return cell
}
else{
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportFaqID") as! SupportCenterFaqTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let faqHead = supportArray[indexPath.section].faqHead
cell.imageText.text = faqHead.capitalized
cell.imageButton.setImage(UIImage(named: supportArray[indexPath.section].faqImage), for: .normal)
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionID") as! SupportQuestionTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.isSelected = true
cell.questionLabel.text = "Q.\(indexPath.row) " + supportArray[indexPath.section].questionArray[indexPath.row - 1].question
cell.answerLabel.text = supportArray[indexPath.section].questionArray[indexPath.row - 1].answer
print(supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl)
if supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl == ""{
cell.urlButton.isHidden = true
}
else{
cell.urlButton.isHidden = false
}
cell.urlButton.isHidden = true
cell.urlButton.tag = indexPath.row
UserDefaults.standard.set(indexPath.section, forKey: "SectionValue")
cell.urlButton.addTarget(self, action: #selector(urlButtonClicked(_:)), for: .touchUpInside)
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if supportArray[indexPath.section].openSection == true{
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = .white
cell.imageButton.tintColor = UIColor(hexString: "#D71B61")
cell.imageText.textColor = UIColor(hexString: "#D71B61")
}
}
supportArray[indexPath.section].openSection = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
}
else{
supportArray[indexPath.section].openSection = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Can anyone provide a solution for this?
do this in didselecterow method. This is the else case of your condition
// You will need to reload multiple sections. So make an array.
var reloadSections = [Int]()
// find already opened array
if let alreadyOpenSection = supportArray.firstIndex(where: { (faq) -> Bool in
return faq.openSection
}) {
// if found, toggle the openSections bit
supportArray[alreadyOpenSection].openSection = false
// add it to reload sections array
reloadSections.append(alreadyOpenSection)
}
supportArray[indexPath.section].openSection = true
reloadSections.append(indexPath.section)
// create index set with reload sections array
let sections = IndexSet.init(reloadSections)
tableView.reloadSections(sections, with: .fade)
// below code is same
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}

In table view cell data was not loading in screen during it's launch?

In this i am having three sections in a table view in which first section will have addresses and radio buttons if i click on radio button it will active and the particular address will be posting depending on the address selection the third section needs to call the api and load the data in the second table view which is present in third section here the problem is during loading for first time when app launched in simulator it is not loading the third section cell data can any one help me how to reduce the error ?
here is the code for table view class
func numberOfSections(in tableView: UITableView) -> Int
{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
return 3
}else {
return 2
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
if (section == 0) {
return "SHIPPING ADDRESS"
}
else if (section == 2) {
return "SHIPPING METHOD"
}
else {
return ""
}
}
else {
if (section == 0) {
return "SHIPPING ADDRESS"
}
else{
return ""
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0)
{
return shippingArray.count
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false){
if (indexPath.section == 0){
return UITableViewAutomaticDimension
}
else if (indexPath.section == 1){
return 62
}
else {
print(height)
return CGFloat(height)
}
}
else{
if (indexPath.section == 0){
return UITableViewAutomaticDimension
}
else if (indexPath.section == 1){
return 62
}
else {
return 0
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
tableDetails.isHidden = false
activityIndicator.stopAnimating()
let arr = shippingArray[indexPath.row]
cell.deleteButton.tag = indexPath.row
cell.nameLabel.text = arr["name"] as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Any = arr["number"] as AnyObject
cell.mobileNumberLabel.text = "\(mobilenumber)"
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
cell.radioButton.addTarget(self, action: #selector(selectRadioButton(_:)), for: .touchUpInside)
cell.deleteButton.addTarget(self, action: #selector(deleteAction(button:)), for: .touchUpInside)
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}
else
{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
if (checkIsPaymentRadioSelect == true){
let defaultvalue = arr["default"] as! Int
if defaultvalue == 1 {
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
addressSelected = true
tableDetails.tableFooterView?.isHidden = false
}
}
return cell
}
else if (indexPath.section == 1){
let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! CreateNewAddressTableViewCell
cell.newAddressButton.addTarget(self, action: #selector(newAddressAction(_:)), for: .touchUpInside)
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingmethodcell", for: indexPath) as! MethodTableViewCell
cell.delegate = self
cell.boolDelegate = self
cell.shippingTableView.reloadData()
if shippingRadio == true {
cell.select = shippingRadio
cell.boolSelected()
cell.shippingmethodURL()
cell.shippingTableView.reloadData()
}
else{
cell.select = methodRadio
cell.shippingTableView.reloadData()
}
return cell
}
}
in this cell class i had got the api data and is passed to table view as shown in the code now i need to call api during cell selection of address can anyone help me how to clear the error or any alternative for this
var chekIndex:IndexPath?
var arrayss = [String:Any]()
var keys = [String]()
let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"
var delegate: CheckoutDelegate?
var heightConstant: Int?
var name = [String]()
var totalCount = 0
var radioSelected:Bool?
var radioSelection: Bool?
var boolDelegate: BoolValidationDelegate?
var select:Bool?
override func awakeFromNib() {
super.awakeFromNib()
radioSelection = false
self.shippingmethodURL()
shippingTableView.delegate = self
shippingTableView.dataSource = self
shippingTableView.rowHeight = UITableViewAutomaticDimension
shippingTableView.estimatedRowHeight = shippingTableView.rowHeight
// Initialization code
}
func paymentRadioAction(button : KGRadioButton) {
_ = button.center
let centralPoint = button.superview?.convert(button.center, to:self.shippingTableView)
let indexPath = self.shippingTableView.indexPathForRow(at: centralPoint!)
if button.isSelected {
} else{
chekIndex = indexPath
radioSelection = true
self.shippingTableView.reloadData()
self.boolDelegate?.boolvalidation(bool: radioSelection!)
}
}
func shippingmethodURL() {
guard let url = URL(string: self.urlString) else {return}
URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
if let data = data, let jsonObj = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:Any] {
self.arrayss = jsonObj
self.keys = Array(jsonObj.keys)
for value in jsonObj.values {
if let array = value as? [[String:Any]] {
for element in array {
if (element["name"] as? String) != nil {
self.totalCount += 1
}
}
}
}
DispatchQueue.main.async {
self.shippingTableView.reloadData()
let sectionHeight = self.arrayss.count * 31
let cellHeight = self.totalCount * 44
self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)
self.heightConstant = Int(self.shippingHeightConstraint.constant)
self.delegate?.heightConstant(int: self.heightConstant!)
}
}
}).resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return arrayss.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.keys[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let key = self.keys[section]
let a :[Any] = arrayss[key] as! [Any]
return a.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
let key = self.keys[indexPath.section]
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row] as! [String:Any]
let name = dictionary["name"]
let price = dictionary ["price"]
cell.methodLabel.text = name as? String
cell.priceLabel.text = price as? String
cell.radioButton.addTarget(self, action: #selector(paymentRadioAction(button:)), for: .touchUpInside)
if chekIndex == indexPath {
cell.radioButton.isSelected = true
} else {
cell.radioButton.isSelected = false
}
return cell
}
and the first time image loading is shown below
!enter image description here ]1
and if i select another radio button in first section it was working fine as expected and image is shown below

How to get cells with different cell classes

I need to get the text from the textfield i.e from KgCustomCell and KgRepsCustomCell. I need to fetch the data from the field, when i run the buttonClicked method.
I have tried to add to instance variables, which contains kg and reps, but the first time i click the button, it's empty. The second time it's okay. But how can i load the data in the most correct way?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let index = indexPath.row
if indexPath.row == 0 && indexPath.section == 0 {
let exerciseName = tableView.dequeueReusableCellWithIdentifier("Exercise Name", forIndexPath: indexPath) as! LoggedExerciseNameCell
exerciseName.lblExerciseName.text = self.exercise?.name
return exerciseName
}
if index == 0 && indexPath.section == 1 {
let txtFieldKg = tableView.dequeueReusableCellWithIdentifier("Text KG", forIndexPath: indexPath) as! KgCustomCell
return txtFieldKg
}
if index == 1 && indexPath.section == 1 {
let txtFieldReps = tableView.dequeueReusableCellWithIdentifier("Text Reps", forIndexPath: indexPath) as! KgRepsCustomCell
//kg = txtFieldReps.textReps.text
return txtFieldReps
}
if index == 2 && indexPath.section == 1 {
let btnLog = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath) as! ButtonLogWorkoutCustomCell
btnLog.btnLogExercise.addTarget(self, action: #selector(AddLogViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
// kg = txtFieldReps.textReps.text
return btnLog
}
if indexPath.section == 2 {
let loggedExerciseInformation = tableView.dequeueReusableCellWithIdentifier("Logged Exercise", forIndexPath: indexPath) as! LoggedExerciseCustomCell
return loggedExerciseInformation
}
let noCell = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath)
return noCell
}
func buttonClicked(sender:UIButton) {
let button = sender as UIButton
if let superview = button.superview {
if (superview.superview as? ButtonLogWorkoutCustomCell) != nil {
try! LogManagerDAO.sharedInstance.realm.write({
exercise?.loggedKg = 4//Int(txtKG.text!)!
exercise?.loggedReps = 4//Int(txtReps.text!)!
log!.addExerciseToLog(exercise!)
loadLoggedExercise()
tableView.reloadData()
})
}
}
}
If you just want the text of that textField than you can use delegate method of UITextField like this, first declare two instance var for that 2 textField's value
var strKG: String = ""
var strReps: String = ""
Now set delegate with textField in cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let index = indexPath.row
if indexPath.row == 0 && indexPath.section == 0 {
let exerciseName = tableView.dequeueReusableCellWithIdentifier("Exercise Name", forIndexPath: indexPath) as! LoggedExerciseNameCell
exerciseName.lblExerciseName.text = self.exercise?.name
return exerciseName
}
if index == 0 && indexPath.section == 1 {
let txtFieldKg = tableView.dequeueReusableCellWithIdentifier("Text KG", forIndexPath: indexPath) as! KgCustomCell
txtFieldReps.textField.tag = index
txtFieldKg.textField.delegate = self
return txtFieldKg
}
if index == 1 && indexPath.section == 1 {
let txtFieldReps = tableView.dequeueReusableCellWithIdentifier("Text Reps", forIndexPath: indexPath) as! KgRepsCustomCell
txtFieldReps.textField.tag = index
txtFieldReps.textField.delegate = self
return txtFieldReps
}
if index == 2 && indexPath.section == 1 {
let btnLog = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath) as! ButtonLogWorkoutCustomCell
btnLog.btnLogExercise.addTarget(self, action: #selector(AddLogViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
// kg = txtFieldReps.textReps.text
return btnLog
}
if indexPath.section == 2 {
let loggedExerciseInformation = tableView.dequeueReusableCellWithIdentifier("Logged Exercise", forIndexPath: indexPath) as! LoggedExerciseCustomCell
return loggedExerciseInformation
}
let noCell = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath)
return noCell
}
Now add delegate method of UITextField
func textFieldDidEndEditing(textField: UITextField) {
if(textField.tag == 0) {
self.strKG = textField.text
}
else {
self.strReps = textField.text
}
}
Now just use this two string object in your button action method.

Transferring UITableView Section to Another TableView

I am currently set up to transfer section 1 of my tableview to another tableView. This is done by moving the didSelectRow: rows. However, the issue is that when I attempt to move the section when every row is selected (and there is nothing in section 0) it crashes with an index is beyond bounds error.
I am using a boilerPlate code for my sectionHeaders due to section 1 header changing back to section 0 header when all items selected in section 1. I believe this is what is causing the index to be out of bounds error, but am not sure how to correct it.
My sections are set up as:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = frc.sections?.count
return numberOfSections!
}
//Table Section Headers
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
let sectionHeader = "Items Needed - #\(frc.sections![section].numberOfObjects)"
let sectionHeader1 = "Items in Cart - #\(frc.sections![section].numberOfObjects)"
if (frc.sections!.count > 0) {
let sectionInfo = frc.sections![section]
if (sectionInfo.name == "0") {
return sectionHeader
} else {
return sectionHeader1
}
} else {
return nil
}
}
with my didSelectRow and cells as:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SLTableViewCell
//assign delegate
cell.delegate = self
let items = frc.objectAtIndexPath(indexPath) as! List
cell.backgroundColor = UIColor.clearColor()
cell.tintColor = UIColor.grayColor()
cell.cellLabel.text = "\(items.slitem!) - Qty: \(items.slqty!)"
cell.cellLabel.font = UIFont.systemFontOfSize(25)
moveToPL.hidden = true
if (items.slcross == true) {
cell.accessoryType = .Checkmark
cell.cellLabel.textColor = UIColor.grayColor()
cell.cellLabel.font = UIFont.systemFontOfSize(20)
self.tableView.rowHeight = 50
moveToPL.hidden = false
} else {
cell.accessoryType = .None
cell.cellLabel.textColor = UIColor.blackColor()
cell.cellLabel.font = UIFont.systemFontOfSize(25)
self.tableView.rowHeight = 60
moveToPL.hidden = true
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let items = frc.objectAtIndexPath(indexPath) as! List
if (items.slcross == true) {
items.slcross = false
} else {
items.slcross = true
}
tableView.reloadData()
}
Is this my issue or is something else causing this?
Edit:
I tried changing my function in charge of moving items from this:
#IBAction func moveToPantry(sender: AnyObject) {
let sectionInfo = self.frc.sections![1]
let objectsToAppend = sectionInfo.objects as! [List]
for item in objectsToAppend {
item.slist = true
item.slcross = false
item.plist = false
item.slitem = item.pitem
item.slqty = item.pqty
item.sldesc = item.pdesc
item.slprice = item.pprice
item.slminqty = item.pminstepperlabel
}
}
to:
#IBAction func moveToSL(sender: AnyObject) {
if (frc.sections!.count > 0) {
let sectionInfo = self.frc.sections![1]
if (sectionInfo.name == "0") {
let objectsToAppend = sectionInfo.objects as! [List]
for item in objectsToAppend {
item.slist = true
item.slcross = false
item.plist = false
item.slitem = item.pitem
item.slqty = item.pqty
item.sldesc = item.pdesc
item.slprice = item.pprice
item.slminqty = item.pminstepperlabel
}
}
}
}
It is still throwing the error. It will move all the objects as long as section 0 isn't empty. Any more help in figuring this out would be appreciated! Thanks in advance.

Resources