Can not update the value in class - ios

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?

Related

how to get main tableview index in nested tableview in swift

I am new in swift and I am not able to get main tableview index on nested tableview button click
my code is like this
extension Section2QuestionsViewController: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrFinancialYears.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let strCellID = "Section2QuestionCell"
var cell = tableView.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
if cell == nil
{
tableSection2.register(Section2QuestionCell.self, forCellReuseIdentifier: strCellID)
cell = tableSection2.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
}
let dictAppStats = arrFinancialYears[indexPath.row] as? [String:Any]
cell?.lblQuestionTitle.text = "\(indexPath.row + 1). \(dictAppStats?["question"] as? String ?? "")"
cell?.arrCourses = [Any]()
cell?.arrCourses = dictAppStats?["options"] as? [Any] ?? []
cell?.tableInsideHeightConstraints.constant = CGFloat(28 * (cell?.arrCourses.count ?? 0))
cell?.tableInside.reloadData()
return cell!
}
}
Inside tableview
extension Section2QuestionCell: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrCourses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InsideSection2QuestionCell", for: indexPath) as! InsideSection2QuestionCell
cell.selectionStyle = .none
let dictFeeStats = arrCourses[indexPath.row] as? [String:Any]
cell.lblOption.text = dictFeeStats?["option_value"] as? String
cell.btnOption.tag = indexPath.item
cell.btnOption.addTarget(self, action: #selector(btnOptionClick), for: .touchUpInside)
cell.lblAnswerKey.text = dictFeeStats?["answer_key"] as? String
cell.lblQuestionId.text = dictFeeStats?["question_id"] as? String
cell.lblAnswerId.text = dictFeeStats?["option_id"] as? String
return cell
}
}
Button Click
#objc func btnOptionClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: InsideSection2QuestionCell = tableInside.cellForRow(at: index) as! InsideSection2QuestionCell
let QuestionId = cell.lblQuestionId.text
let AnswwerId = cell.lblAnswerId.text
print(QuestionId as Any)
print(AnswwerId as Any)
Globalnewdict = ["option":AnswwerId as Any,"question":QuestionId as Any]
Globalindexvalue = sender.tag
NotificationCenter.default.post(name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)
tableInside.reloadData()
}
I am not able to get main tableview index path value on button. Is there is any way to get main tableview index path value on button click.
Please help
Thanks in Advance!
You could add an index path object in your Section2QuestionCell
var parentTableIndexPath : IndexPath!
Then set the value in cellForRowAt tableview delegate method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let strCellID = "Section2QuestionCell"
var cell = tableView.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
if cell == nil {
tableSection2.register(Section2QuestionCell.self, forCellReuseIdentifier: strCellID)
cell = tableSection2.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
}
cell.parentTableIndexPath = indexPath
let dictAppStats = arrFinancialYears[indexPath.row] as? [String:Any]
cell?.lblQuestionTitle.text = "\(indexPath.row + 1). \(dictAppStats?["question"] as? String ?? "")"
cell?.arrCourses = [Any]()
cell?.arrCourses = dictAppStats?["options"] as? [Any] ?? []
cell?.tableInsideHeightConstraints.constant = CGFloat(28 * (cell?.arrCourses.count ?? 0))
cell?.tableInside.reloadData()
return cell!
}
Since btnOptionClick() is in same class, you can directly access the parent table Index path in your button action.
In
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let strCellID = "Section2QuestionCell"
var cell = tableView.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
if cell == nil
{
tableSection2.register(Section2QuestionCell.self, forCellReuseIdentifier: strCellID)
cell = tableSection2.dequeueReusableCell(withIdentifier: strCellID) as? Section2QuestionCell
}
let dictAppStats = arrFinancialYears[indexPath.row] as? [String:Any]
cell?.lblQuestionTitle.text = "\(indexPath.row + 1). \(dictAppStats?["question"] as? String ?? "")"
cell?.arrCourses = [Any]()
cell?.arrCourses = dictAppStats?["options"] as? [Any] ?? []
cell?.tableInsideHeightConstraints.constant = CGFloat(28 * (cell?.arrCourses.count ?? 0))
cell?.tableInside.tag = indexPath.row
cell?.tableInside.reloadData()
return cell!
}
In ButtonClick
#objc func btnOptionClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: InsideSection2QuestionCell = tableInside.cellForRow(at: index) as! InsideSection2QuestionCell
let QuestionId = cell.lblQuestionId.text
let AnswwerId = cell.lblAnswerId.text
print(QuestionId as Any)
print(AnswwerId as Any)
Globalnewdict = ["option":AnswwerId as Any,"question":QuestionId as Any]
Globalindexvalue = tableInside.tag
NotificationCenter.default.post(name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)
tableInside.reloadData()
}
In cellForRowAt I set indexpath.row to tableview.tag.
Then on button click I set tableview.tag to global indexpath.

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

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

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
}

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.

Resources