Showing the same content in the every cells while scrolling the cells - ios

I have 5 types of tableview cells.And i ave one basecell.
BaseCell:-
import UIKit
class BaseCell: UITableViewCell {
// MARK: Internal Properties
var type: CellType!
var textChangedBlock: ((String) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setOptions(Options1:NH_OptionsModel){}
func setOptions(OptionsSelected:NH_OptionsModel){}
func setOptions1(OptionsSelected:NH_OptionsModel){}
func setOptions(OptionsisSelected:NH_OptionsModel){}
func setOptions1(OptionsisSelected:NH_OptionsModel){}
}
One Tableviewcell:-
class RadioTypeCell: BaseCell {
var actionBlock: (() -> Void)?
#IBOutlet weak var optionLabel: UILabel?
#IBOutlet weak var buttonType: UIButton?
override func setOptions(Options1:NH_OptionsModel) {
self.optionLabel?.text = Options1.values
}
override func setOptions1(OptionsSelected:NH_OptionsModel) {
self.buttonType?.isHidden = false
buttonType?.setBackgroundImage(UIImage(named: "radio_check.png"), for: .normal)
print(OptionsSelected.isSelected)
OptionsSelected.isSelected = true
print(OptionsSelected.isSelected)
}
override func setOptions(OptionsisSelected:NH_OptionsModel) {
self.buttonType?.isHidden = false
buttonType?.setBackgroundImage(UIImage(named: "radio_uncheck.png"), for: .normal)
print(OptionsisSelected.isSelected)
OptionsisSelected.isSelected = false
print(OptionsisSelected.isSelected)
}
#IBAction func onActionButton(btn: UIButton) {
print("click the cell")
actionBlock?()
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
In viewcontroller:-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
print(model.answerType)
print(model.answerType?.rawValue)
let c = model.answerType
let cellClass = c?.cellType().getClass()
print(cellClass)
let cell = tableView.dequeueReusableCell(withIdentifier: (cellClass?.cellReuseIdentifier())!, for: indexPath) as! BaseCell
print(cell)
let optionModel = questionViewModel.datafordisplay(atindex: indexPath)
cell.setOptions(Options1: optionModel)
cell.type = c?.cellType()
currentCell(c: cell, index: indexPath.row)
return cell
}
So In the tableview cell ,it contain
the following things.
1.One button
2.Label(Here showing the options)
So while selecting the one option i will click on the button,at that time the button has set the background image.Initially the image will be radio button with uncheck after while clicking the button the button image becomes radio button check.
And i given the code in the didselect the cell from the tableview.
Now my problem is after selecting the cells and then scrolling the tableview .The cells content is not refreshing .How to solve the problem.
And my tableview has sections.
My model:-
import UIKit
typealias JSONDictionary = [String:Any]
enum AnswerType:Int
{
case CheckBoxCell = 1
case RadioTypeCell
case SmileyTypeCell
case StarRatingTypeCell
case TextTypeCell
func cellType() -> CellType{
switch self {
case .CheckBoxCell: return .checkboxtype
case .RadioTypeCell :return .radiotype
case .SmileyTypeCell: return .smileytype
case .StarRatingTypeCell: return .starratingtype
case .TextTypeCell: return .textfieldtype
default: return .radiotype
}
}
}
class QuestionListModel: NSObject {
var dataListArray33:[NH_OptionsModel] = []
var id:Int!
var question:String!
var buttontype:String!
var options:[String]?
var v:String?
var answerType:NHAnswerType?
var optionsModelArray:[OptionsModel] = []
init(dictionary :JSONDictionary) {
guard let question = dictionary["question"] as? String,
let typebutton = dictionary["button_type"] as? String,
let id = dictionary["id"] as? Int
else {
return
}
self.answerType = AnswerType(rawValue: Int(typebutton)!)
if let options = dictionary["options"] as? [String]{
print(options)
print(options)
for values in options{
print(values)
let optionmodel = OptionsModel(values: values)
self.optionsModelArray.append(optionmodel)
}
}
self.buttontype = typebutton
self.question = question
self.id = id
}
}
my viewmodel:-
var OptionListArray:Array<OptionsModel>? = []
init(withdatasource newDatasourceModel:QuestionDataSourceModel,withmodel model:HomeModel) {
datasourceModel = newDatasourceModel
homemodel1 = model
print(homemodel1)
print(datasourceModel.dataListArray)
}
func numberOfSections() -> Int{
print((datasourceModel.dataListArray?.count)!)
return (datasourceModel.dataListArray?.count)!
}
func titleForHeaderInSection(atsection section: Int) -> QuestionListModel {
return datasourceModel.dataListArray![section]
}
func numberOfRowsIn(section:Int) -> Int {
print( datasourceModel.dataListArray?[section].optionsModelArray.count ?? 0)
return datasourceModel.dataListArray?[section].optionsModelArray.count ?? 0
// return self.questionsModelArray?[section].optionsModelArray.count ?? 0
}
func datafordisplay(atindex indexPath: IndexPath) -> NH_OptionsModel{
print(datasourceModel.dataListArray![indexPath.section].optionsModelArray[indexPath.row])
return datasourceModel.dataListArray![indexPath.section].optionsModelArray[indexPath.row]
}
didselect tableview:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
if questionViewModel.isselected == true{
let selectedIndexPathAtCurrentSection = questionViewModel.selectedIndexPaths.filter({ $0.section == indexPath.section})
for indexPath in selectedIndexPathAtCurrentSection {
tableview.deselectRow(at: indexPath, animated: true)
if let indexOf = questionViewModel.selectedIndexPaths.index(of: indexPath) {
questionViewModel.selectedIndexPaths.remove(at: indexOf)
let questionModel = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
questionViewModel.question = questionModel.question
questionViewModel.insertQuestList(answer: questionViewModel.question!, Index: indexPath.section)
let c = questionModel.answerType
print(c)
let cellClass = c?.cellType().getClass()
print(cellClass)
let cell = tableview.cellForRow(at: indexPath) as? BaseCell
print(cell)
// let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell
questionViewModel.button = questionModel.buttontype
let value: Int = questionModel.id
let string = String(describing: value)
questionViewModel.question_id = string
questionViewModel.question = questionModel.question
let model = questionViewModel.datafordisplay(atindex: indexPath)
if questionModel.buttontype == "2" {
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions(OptionsisSelected:questionViewModel.datafordisplay(atindex: indexPath))
}
else if questionModel.buttontype == "1"{
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions1(OptionsisSelected:questionViewModel.datafordisplay(atindex: indexPath))
}
questionViewModel.isselected = model.isSelected!
}
}
questionViewModel.selectedIndexPaths.append(indexPath)
let questionModel = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
let c = questionModel.answerType
print(c)
let cellClass = c?.cellType().getClass()
print(cellClass)
let cell = tableview.cellForRow(at: indexPath) as? BaseCell
print(cell)
let model = questionViewModel.datafordisplay(atindex: indexPath)
if questionModel.buttontype == "1"{
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
}
else if questionModel.buttontype == "2"{
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions1(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
// }
print(questionViewModel.answers1)
}
questionViewModel.isselected = model.isSelected!
questionViewModel.question = questionModel.question
questionViewModel.questionlist(answer: questionViewModel.question!)
questionViewModel.insertQuestList(answer: questionModel.question, Index: indexPath.section)
let value: Int = questionModel.id
let string = String(describing: value)
questionViewModel.question_id = string
questionViewModel.question(answer: questionViewModel.question_id!)
questionViewModel.questIdList(answer: questionViewModel.question_id!, Index: indexPath.section)
questionViewModel.button = questionModel.buttontype
}
// False condition
else if questionViewModel.isselected == false{
let questionModel = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
questionViewModel.question = questionModel.question
questionViewModel.insertQuestList(answer: questionViewModel.question!, Index: indexPath.section)
let c = questionModel.answerType
print(c)
let cellClass = c?.cellType().getClass()
print(cellClass)
let cell = tableview.cellForRow(at: indexPath) as? BaseCell
print(cell)
let model = questionViewModel.datafordisplay(atindex: indexPath)
print(model.values)
if questionModel.buttontype == "1"{
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
print(questionViewModel.answers1)
}
//Radio Button
else if questionModel.buttontype == "2"{
questionViewModel.insertStrng(answer: model.values!, Index: indexPath.section)
cell?.setOptions1(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
// }
print(questionViewModel.answers1)
}
questionViewModel.isselected = model.isSelected!
let value: Int = questionModel.id
let string = String(describing: value)
questionViewModel.question_id = string
questionViewModel.question(answer: questionViewModel.question_id!)
questionViewModel.questIdList(answer: questionViewModel.question_id!, Index: indexPath.section)
questionViewModel.button = questionModel.buttontype
questionViewModel.selectedIndexPaths.append(indexPath)
}
}

Make sure your model object value is update on button clicked event and you need to update cell ui in Cell at index.
Here is reference code for how to update ui at cell at index.
Note: Code is not checked in xcode so may be some minor error.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
print(model.answerType)
print(model.answerType?.rawValue)
let c = model.answerType
let cellClass = c?.cellType().getClass()
print(cellClass)
let cell = tableView.dequeueReusableCell(withIdentifier: (cellClass?.cellReuseIdentifier())!, for: indexPath) as! BaseCell
print(cell)
let optionModel = questionViewModel.datafordisplay(atindex: indexPath)
cell.setOptions(Options1: optionModel)
if optionModel.isSelected {
cell.setOptions1(OptionsisSelected:optionModel)
} else {
cell.setOptions(OptionsisSelected:optionModel)
}
cell.type = c?.cellType()
currentCell(c: cell, index: indexPath.row)
return cell
}

Related

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
}
}

Can not update the value in class

This is my class Designed.
open class SBCity: NSObject {
var CM_CityID:String = ""
var CM_CityName:String = ""
var CM_OrderBy:Int = 0
required public init(CM_CityID:String,CM_CityName:String,CM_OrderBy:Int) {
self.CM_CityID = CM_CityID
self.CM_CityName = CM_CityName
self.CM_OrderBy = CM_OrderBy
}
}
ViewController
In the ViewController I have the tableView contain the following three details in each cell. I just append the value in the class on my UITableView didSelect method.
var source:SBCity?
var destination:SBCity?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if filterdata.count != 0 {
return filterdata.count
} else {
if tableView == FirstTable {
return ArrcityList.count
} else {
return ArrcityList.count
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == FirstTable{
let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCityCell") as! RecentCityCell
cell.cities = ArrcityList[indexPath.row]
return cell
}
//if tableView is not table1 then
if filterdata.count != 0 {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "SourceCityCell")
as! SourceCityCell
cell2.cities = filterdata[indexPath.row]
return cell2
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "SourceCityCell")
as! SourceCityCell
cell2.cities = ArrcityList[indexPath.row]
return cell2
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isSelectingSource {
if tableView == FirstTable{
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! RecentCityCell
self.source = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
source = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
SourceCityName = crrtCell.lblCity1.text!
self.moveOnNextVc()
} else {
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! SourceCityCell
self.source = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
source = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
SourceCityName = crrtCell.lblCity2.text!
self.moveOnNextVc()
}
} else if isSelectingDestination {
if tableView == FirstTable{
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! RecentCityCell
self.destination = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
destination = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
DestinationCityName = crrtCell.lblCity1.text!
self.moveOnNextVc()
} else {
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! SourceCityCell
self.destination = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
destination = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
DestinationCityName = crrtCell.lblCity2.text!
self.moveOnNextVc()
}
}
}
But it does not append the value in the class. it's showing nil every time. What's the wrong with the code?

must register a nib or a class for the identifier or connect a prototype cell in a storyboard in swift

My model:
enum NHAnswerType:Int
{
case NHAnswerCheckboxButton = 1
case NHAnswerRadioButton = 2
case NHAnswerSmileyButton = 3
case NHAnswerStarRatingButton = 4
case NHAnswerTextButton = 5
}
class NH_QuestionListModel: NSObject {
var dataListArray33:[NH_OptionsModel] = []
var id:Int!
var question:String!
var buttontype:String!
var options:[String]?
var v:String?
var answerType:NHAnswerType?
var optionsModelArray:[NH_OptionsModel] = []
init(dictionary :JSONDictionary) {
guard let question = dictionary["question"] as? String,
let typebutton = dictionary["button_type"] as? String,
let id = dictionary["id"] as? Int
else {
return
}
// (myString as NSString).integerValue
self.answerType = NHAnswerType(rawValue: Int(typebutton)!)
print(self.answerType?.rawValue)
if let options = dictionary["options"] as? [String]{
print(options)
print(options)
for values in options{
print(values)
let optionmodel = NH_OptionsModel(values: values)
self.optionsModelArray.append(optionmodel)
}
}
self.buttontype = typebutton
self.question = question
self.id = id
}
}
In viewcontroller:
override func viewDidLoad() {
super.viewDidLoad()
self.tableview?.register(NH_SmileyCell.nib, forCellReuseIdentifier: NH_SmileyCell.identifier)
self.tableview?.register(NH_StarRatingCell.nib, forCellReuseIdentifier: NH_StarRatingCell.identifier)
self.tableview?.register(NH_CheckBoxCell.nib, forCellReuseIdentifier: NH_CheckBoxCell.identifier)
self.tableview?.register(NH_RadioTypeCell.nib, forCellReuseIdentifier: NH_RadioTypeCell.identifier)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.row)
// print(model.answerType?.hashValue)
print(model.answerType)
print(model.answerType?.rawValue)
switch model.answerType {
case .NHAnswerRadioButton?:
if let cell = tableview.dequeueReusableCell(withIdentifier: NH_RadioTypeCell.identifier, for: indexPath) as? NH_RadioTypeCell {
cell.textLabel?.text = "dfdsfgs"
// cell.item = item
return cell
}
case .NHAnswerCheckboxButton?:
if let cell = tableView.dequeueReusableCell(withIdentifier: NH_CheckBoxCell.identifier, for: indexPath) as? NH_CheckBoxCell {
cell.textLabel?.text = "dfdsfgs"
// cell.item = item
return cell
}
case .NHAnswerSmileyButton?:
if let cell = tableView.dequeueReusableCell(withIdentifier: NH_SmileyCell.identifier, for: indexPath) as? NH_SmileyCell {
cell.textLabel?.text = "dfdsfgs"
// cell.item = item
return cell
}
case .NHAnswerStarRatingButton?:
if let cell = tableView.dequeueReusableCell(withIdentifier: NH_StarRatingCell.identifier, for: indexPath) as? NH_StarRatingCell {
cell.textLabel?.text = "dfdsfgs"
// cell.item = item
return cell
}
// case .NHAnswerTextButton?:
// if let cell = tableView.dequeueReusableCell(withIdentifier: NH_TextCell.identifier, for: indexPath) as? NH_TextCell{
// // cell.item = item
// return cell
// }
default:
return UITableViewCell()
}
And in the radiotypecell:
class NH_RadioTypeCell: UITableViewCell {
#IBOutlet weak var questionLabel: UILabel?
var item: NH_QuestionViewModelItem? {
didSet {
guard let item = item as? NHQuestionViewModelQuestionNameItem else {
return
}
questionLabel?.text = item.question
}
}
static var nib:UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This always produces the following error message:
NH_CheckBoxCell - must register a nib or a class for the identifier or
connect a prototype cell in a storyboard'
How can I fix the problem?
What changes should I do in while registration of the cell in the tableview in swift?

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 send each tableViewcell data to collectionview in swift3

I have created dynamic forms, user enter number of forms, and i have created table cell for that. After submitting the all forms, all details should show in excel formate, for that i have created collection view but issue is that the only selected cell value is printing.
I use this for collectionView
https://github.com/brightec/CustomCollectionViewLayout
tableViewController.swift
struct Information {
var name: String
var phone: String
var email: String
var gender: String
init(name: String, phone: String, email: String, gender: String) {
self.name = name
self.phone = phone
self.gender = gender
self.email = email
}
import UIKit
class tableViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var tableView: UITableView!
#IBOutlet var nameText: UITextField!
var name: String = ""
var phone: String = ""
var email: String = ""
var gender: String = ""
var shop = Int()
var namevalue = String()
var phoneValue = String()
var emailValue = String()
var genderValue = String()
var formData: [Information] = []
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return shop
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let shop1 = [shop]
return "Section \(shop1[section]))"
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! myTableViewCell
if indexPath.section == 0{
if indexPath.row == 0{
print("THis is print 1",cell.emailText.text as Any)
}
}
name = cell.nameText.text!
phone = cell.phoneText.text!
email = cell.emailText.text!
gender = cell.genderText.text!
print("This is name",name)
let data = Information(name: name, phone: phone, email: email, gender: gender)
formData.append(data)
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for _ in 0..<shop {
print("THis is print 3",shop)
}
let indexPath = tableView.indexPathForSelectedRow //optional, to get from any UIButton for example
let currentCell = tableView.cellForRow(at: indexPath!)! as! myTableViewCell
name = currentCell.nameText.text!
phone = currentCell.phoneText.text!
email = currentCell.emailText.text!
gender = currentCell.genderText.text!
print("Hello hello3",formData)
print("THis is print 4",currentCell.self.emailText.text as Any)
tableView.reloadData()
}
#IBAction func submitButton(_ sender: Any) {
tableView.reloadData()
print("THis is print 6",formData)
let mainController : CollectionViewController = CollectionViewController(nibName: "CollectionViewController", bundle: nil)
mainController.getShop = shop+1
mainController.formData = formData
// mainController.getPhone = phone
// mainController.getEmail = email
// mainController.getGender = gender
self.navigationController?.pushViewController(mainController, animated: true)}}
collectionViewController.swift
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var formData: [Information] = []
let dateCellIdentifier = "DateCellIdentifier"
let contentCellIdentifier = "ContentCellIdentifier"
#IBOutlet weak var collectionView: UICollectionView!
var getShop = Int()
var getName = String()
var getPhone = String()
var getEmail = String()
var getGender = String()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView .register(UINib(nibName: "DateCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: dateCellIdentifier)
self.collectionView .register(UINib(nibName: "ContentCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: contentCellIdentifier)
}
// MARK - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return getShop
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
for element in formData{
print("This is element",element.name)
}
if indexPath.section == 0 {
if indexPath.row == 0 {
let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
dateCell.backgroundColor = UIColor.white
dateCell.dateLabel.font = UIFont.systemFont(ofSize: 13)
dateCell.dateLabel.textColor = UIColor.black
dateCell.dateLabel.text = "Number"
return dateCell
}
if indexPath.row == 1 {
let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
dateCell.backgroundColor = UIColor.white
dateCell.dateLabel.font = UIFont.systemFont(ofSize: 13)
dateCell.dateLabel.textColor = UIColor.black
dateCell.dateLabel.text = "Name"
return dateCell
}
if indexPath.row == 2 {
let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
dateCell.backgroundColor = UIColor.white
dateCell.dateLabel.font = UIFont.systemFont(ofSize: 13)
dateCell.dateLabel.textColor = UIColor.black
dateCell.dateLabel.text = "Phone"
return dateCell
}
if indexPath.row == 3 {
let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
dateCell.backgroundColor = UIColor.white
dateCell.dateLabel.font = UIFont.systemFont(ofSize: 13)
dateCell.dateLabel.textColor = UIColor.black
dateCell.dateLabel.text = "Email"
return dateCell
}else {
let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
contentCell.contentLabel.font = UIFont.systemFont(ofSize: 13)
contentCell.contentLabel.textColor = UIColor.black
contentCell.contentLabel.text = "Gender"
if indexPath.section % 2 != 0 {
contentCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
contentCell.backgroundColor = UIColor.white
}
return contentCell
}
} else {
if indexPath.row == 0 {
let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
dateCell.dateLabel.font = UIFont.systemFont(ofSize: 13)
dateCell.dateLabel.textColor = UIColor.black
dateCell.dateLabel.text = String(indexPath.section)
if indexPath.section % 2 != 0 {
dateCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
dateCell.backgroundColor = UIColor.white
}
return dateCell
}
else if indexPath.row == 1
{
let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
contentCell.contentLabel.font = UIFont.systemFont(ofSize: 13)
contentCell.contentLabel.textColor = UIColor.black
contentCell.contentLabel.text = getName
if indexPath.section % 2 != 0 {
contentCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
contentCell.backgroundColor = UIColor.white
}
return contentCell
}
else if indexPath.row == 2
{
let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
contentCell.contentLabel.font = UIFont.systemFont(ofSize: 13)
contentCell.contentLabel.textColor = UIColor.black
contentCell.contentLabel.text = getPhone
if indexPath.section % 2 != 0 {
contentCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
contentCell.backgroundColor = UIColor.white
}
return contentCell
}
else if indexPath.row == 3
{
let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
contentCell.contentLabel.font = UIFont.systemFont(ofSize: 13)
contentCell.contentLabel.textColor = UIColor.black
contentCell.contentLabel.text = getEmail
if indexPath.section % 2 != 0 {
contentCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
contentCell.backgroundColor = UIColor.white
}
return contentCell
}
else {
let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
contentCell.contentLabel.font = UIFont.systemFont(ofSize: 13)
contentCell.contentLabel.textColor = UIColor.black
contentCell.contentLabel.text = getGender
if indexPath.section % 2 != 0 {
contentCell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
contentCell.backgroundColor = UIColor.white
}
return contentCell
}}}}
1.I Entered number of form i want
2. no of forms displayed and i entered all different values for all different forms
3.But what happening is only one form details are printing
You shouldn't get your data in public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Because when you scroll up / down, this func will call again and again.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let k = indexPath.row+1
let j:String? = String(k)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! myTableViewCell
cell.formNoLabel.text = j
for indexPath in 0..<shop{
print(String(indexPath))
}
if indexPath.section == 0{
if indexPath.row == 0{
print("THis is print 1",cell.emailText.text as Any)
}
}
var data : Information
if indexPath.row < formData.count {
data = formData[indexPath.row]
} else {
data = Information(name: name, phone: phone, email: email, gender: gender)
formData.append(data)
}
cell.data = data
print("THis is print 2",formData)
//cell.nameLabel.text = Array[indexPath.row]
// cell.nameText.text = Array[indexPath.row]
return cell
}
And in myTableViewCell class, you should change to
class myTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet var nameLabel: UILabel!
#IBOutlet var nameText: UITextField!
#IBOutlet var phoneText: UITextField!
#IBOutlet var emailText: UITextField!
#IBOutlet var genderText: UITextField!
#IBOutlet var formNoLabel: UILabel!
var data: Information! {
didSet {
nameText.text = data.name
phoneText.text = data.phone
emailText.text = data.email
genderText.text = data.gender
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
nameText.delegate = self
phoneText.delegate = self
emailText.delegate = self
genderText.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let indexPath = tableView.indexPathForSelectedRow //optional, to get from any UIButton for example
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
print(currentCell.textLabel!.text!)
}
func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text!
if textField === nameText {
data.name = text
} else if textField === phoneText {
data.phone = text
} else if textField === emailText {
data.email = text
} else if textField === genderText {
data.gender = text
}
}
}
Remember change struct Information to class Information

Resources