I am new to swift . i am doing my project programatically and I load data from api to the tableView and tableView like ios setting page ..
now i need all rows information when click "Add to cart" button. How can i do it?
here is my code sample :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: cartHeaderCell, for: indexPath) as! CartHeaderCell
cell.configureCell(indexPath.item)
return cell
case 1:
let obj = data?[indexPath.row]
var cell = UITableViewCell()
switch obj {
case is Addon:
cell = tableView.dequeueReusableCell(withIdentifier: addonCell, for: indexPath) as! AddonCell
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
cell.accessoryView = switchView
guard let addon = obj as? Addon else {
return cell
}
cell.textLabel?.text = "\(addon.name) + €\(addon.price)"
case is AddonGroup:
cell = tableView.dequeueReusableCell(withIdentifier: addonGroupCell, for: indexPath) as! AddonGroupCell
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
guard let addonGroup = obj as? AddonGroup else {
return cell
}
if let addons = addonGroup.addonList {
cell.detailTextLabel?.text = ""
var selectedAddons = ""
for _addon in addons
{
if _addon.isSelect == true {
selectedAddons = selectedAddons + "\(_addon.name)"
}
}
cell.detailTextLabel?.text = selectedAddons
}
cell.textLabel?.text = addonGroup.name
...........................................
As Fahim was mentioning, you need to set up a data model that records that status of each cell before / during / after the user interaction with each cell. So when the cell goes off screen and then comes back on, it will be presented with the correct state of the model.
Secondly, for the UISwitchViews, you should be instantiating and adding those to the contentView within each cell in order to keep the cellForRow function clean and problem free. The reason leads me into my next point: how to record the status of each UISwitchView after the user has interacted with a UISwitchView. You are going to want to create a protocol and add a delegate within the UICollectionViewCell(that inherits class and the delegate should be a weak var), in order to update the model whenever the UISwitch is tapped.
If you have any more questions i can do my best to help!
Related
In my view controller I have a table view in which I am loading multiple tableview cells. Some have UITextfield,Labels,Radio and check buttons. Now I have done all the part showing and entering data in tableview cell but not able to check whether any one field is left empty.
On button click in my controller I need to check this validation if all fields are non-empty. Or How can I get data from each field on button click.
Here is my cellForRowAt indexpath code that will give idea of diff cell I am loading. How can I validate if my uitextfield are empty and radio button are checked.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "StartEndDateCell", for: indexPath) as! StartEndDateCell
//cell with 2 textfield
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NameTableViewCell", for: indexPath) as! NameTableViewCell
//cell with single textField
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "StartEnddateTableViewCell", for: indexPath) as! StartEnddateTableViewCell
//cell open UIDATEPICKER here on click of textfield contains 2 textfield
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "AmountTableViewCell", for: indexPath) as! AmountTableViewCell
//cell with single textfield with numeric keyboard
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "MaxFixTableViewCell", for: indexPath) as! MaxFixTableViewCell
return cell
//cell with radio buttons
case 5:
let cell = tableView.dequeueReusableCell(withIdentifier: "infoTableViewCell", for: indexPath) as! infoTableViewCell
//for oneTimeLabel
let tapGestureFrequency : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(freqLblClick(tapGestureFrequency:)))
tapGestureFrequency.delegate = self as? UIGestureRecognizerDelegate
tapGestureFrequency.numberOfTapsRequired = 1
cell.oneTimeLabel.isUserInteractionEnabled = true
cell.oneTimeLabel.tag = 1
cell.oneTimeLabel.addGestureRecognizer(tapGestureFrequency)
//for onLabel
let tapGestureOnDebit : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(lblClickDebit(tapGestureOnDebit:)))
tapGestureOnDebit.delegate = self as? UIGestureRecognizerDelegate
tapGestureOnDebit.numberOfTapsRequired = 1
cell.onLabel.isUserInteractionEnabled = true
cell.onLabel.tag = 2
cell.onLabel.addGestureRecognizer(tapGestureOnDebit)
return cell
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: "RemarksTableViewCell", for: indexPath) as! RemarksTableViewCell
return cell
case 7:
let cell = tableView.dequeueReusableCell(withIdentifier: "InformTableViewCell", for: indexPath) as! InformTableViewCell
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "checkTableViewCell", for: indexPath) as! checkTableViewCell
return cell
}
}
I think you can implement UITextFieldDelegate to track and update your data, for UITableViewCells with UITextField. But this requires you to write implement text delegate in each of the cell where you need to update your data set. Additionally for switch controls and check boxes you can monitor their valueChanged event.
For example
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text, let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange, with: string)
UserData.shared.name = updatedText
}
return true
}
#IBAction func switchValueChanged(_ sender: Any) {
UserData.shared.setting = switchControl.isOn
}
You will need to store this data somewhere, specially because UITableView reuse its cells, so you might lose what was inputed if the user scrolls.
Assuming you have an array where the the info for each cell comes from, you can create a flag that explicits if the user has answered that question. On cellForRowAtindexPath you'll check if the field is empty and reload the answer/state.
After that, you can create a validationMethod that should be called after every cell input, based on your local array of fields + answers.
all other validation like numeric type and date type i have done in cell class. I know it is not the proper way to do it. We can save our values to model class and use model class instead of doing it. doing in this way may reult in failure of validation when we scroll our tableview, but for now it is working in my code. Still I am waiting to do it in a write way. I will not mark my question as answered
at button click
#IBAction func nextButtonClicked(_ sender: Any) {
let nameCell = self.tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as? NameTableViewCell
if (nameCell?.nameTextField.text!.isEmpty)! {
Log.i("TextField is Empty---" )
}
let startEndDateCell = self.tableView.cellForRow(at: IndexPath(row : 2,section : 0)) as? StartEnddateTableViewCell
if((startEndDateCell?.startDateTextField.text!.isEmpty)! || (startEndDateCell?.endDateTextField.text!.isEmpty)!){
Log.i("Start And End Date Empty")
}
let amountCell = self.tableView.cellForRow(at: IndexPath(row : 3, section : 0))as? AmountTableViewCell
if (amountCell?.amountTextField.text!.isEmpty)! {
Log.i("Amount Cell Empty---")
}
else{
let vc = NextViewController(nibName: "NextViewController", bundle: nil)
navigationController?.pushViewController(vc, animated: true )
}
}
I have a Dynamic Prototypes Table view that has different cells, I'm adding the cells to the table view and I want to change their content. All the tutorials I find is for a tableview with only one type of cell, but I have 8 different types. How would I change their content (ie, textfields etc) and how would I get actions from them back to the main tableview controller to do some business logic? (ie button pressed etc)
What I did is:
I created a costume class for each cell type and connected them under customClass, class field.
I attached the textfields etc, actions and references to these classes.
this is my cellAtRow function I assume I would change it in this function somehow?
or reference the classes from here?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print ("indexPath: ", indexPath)
print ("indexPath: ", indexPath[0])
print ("-------")
if (sectionsData[indexPath[0]] == "header") {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "description") {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerInfoCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "diagnoses") {
let cell = tableView.dequeueReusableCell(withIdentifier: "diagnosisCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "perscription") {
let cell = tableView.dequeueReusableCell(withIdentifier: "perscriptionCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "notes") {
let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addFaxHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addFax") {
let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addEmailHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "addEmailCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addEmails") {
let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "givePermissionHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "permissionCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "select answer") {
let cell = tableView.dequeueReusableCell(withIdentifier: "selectAnswerCell", for: indexPath)
return cell
}
You need to use
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as! HeaderTableViewCell
to call cell.yourTextField.text for example
You have to cast your cells to the class they belong. On the second line of the code block you can see an example of this.
if (sectionsData[indexPath[0]] == "header") {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as! HeaderTableViewCell
cell.titleLbl.text = "Title"
cell.delegate = self // To receive actions back
return cell
}
. . . // More of the same
// default return
To send calls back to your main view controller you can add protocols to your cells like so:
protocol HeadTableViewCellProcol{
func bttnPressed()
}
class HeadTableViewCell: UITableViewCell{
var delegate: HeadTableViewCellProcol?
#IBAction func bttnPressedInCell(){
delegate?.bttnPressed()
}
}
The this of this protocols like the protocols you had to implement for your UITableView. You will also have to implement these protocols in your main VC.
You need to cast UITableViewCell into your dynamic cell class. You can try the following:
guard let cell = tableView. dequeueReusableCell(withIdentifier: "perscription", for: indexPath) as? PerscriptionTableViewCell else { return UITableViewCell() }
cell.setupCell() //You have access to cell's public funcs and vars now
return cell
Using optional unwrapping, you can be sure that your app is likely to be safe from type casting crashes.
As the Apple documentation says, the return type of the dequeueReusableCell is a UITableViewCell.
Apple Documentation
Return Value: A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
Your custom cells classes should inherit from UITableViewCell and to be able to use an instance of your custom cell you need to cast the returning UITableViewCell of the dequeReusableCell into your desire custom cell type.
let cell = tableView.dequeueReusableCell(withIdentifier: "customCellIdentifierCell", for: indexPath) as! YourCutsomTableViewCell
For customizing, every cell is responsible for his own configuration. You should have a function (you can use protocols or inherit from a superclass) and inside the cellForRowAtIndexPath, after casting it, call the setup function.
customCell.setup() //you can add some parameters if its needed
I am trying to populate a UITableView prototype cell with "Facebook status". It has images and videos depending on the response from Facebook server. But I am not able to populate it properly.
I will get the first image from the array. But when I scroll down UITableView and reach the top again, the image disappears. And when I print the value of i it exceeds the count of array soon after the tableview is loaded.
I am adding the edited code here.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows : Int = 0
if section < numberOfRowsAtSection.count{
rows = numberOfRowsAtSection[section]
print(section,rows)
}
return rows
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("Section,Row",indexPath.section, indexPath.row)
switch(combinedArray[indexPath.section][indexPath.row]){
case "photo" :
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageDetail", for:indexPath) as! imageCell
if(im < imageDetails.count){
let imageUrl = imageDetails[im]
let url = URL(string:imageUrl)
let data = try? Data(contentsOf: url!)
cell.storyDetailsLbl1.text = photoStoryDetails[im]
print(imageDetails[im])
cell.images1.image = UIImage(data: data!)
}
im = im + 1
return cell
case "video" :
let cell1 = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! videoPlayerCell
cell1.videoView.isHidden = false
if vd < videoURLs.count{
print(videoURLs.count)
let urls = videoURLs[vd]
cell1.videoPlayerItem = AVPlayerItem.init(url: urls)
cell1.videoLabel.text = videoStoryDetails[vd]
}
vd = vd + 1
return cell1
case "link":
let cell2 = tableView.dequeueReusableCell(withIdentifier: "LinkCell", for: indexPath) as! linkCell
if ln < linkDetails.count {
cell2.linkLbl.text = linkDetails[ln]
}
ln = ln + 1
return cell2
default:
let cell3 = tableView.dequeueReusableCell(withIdentifier: "StatusCell", for: indexPath) as! statusCell
if st < statusDetails.count{
cell3.statusLbl.text = statusDetails[st]
}
st = st + 1
return cell3
}
}
Tableviews deque already created cells and reuse them to enhance performance. So a cell with the identifier "ImageDetail" could be reused and populated with data from any of your case statements. This will cause oddities like images disappearing when they shouldn't.
One way to solve this is to ensure you are handling each cell property in every case. cell.storyDetailsLbl1.text isn't handled in the photo case. cell.images1.image isn't handled in the link case, etc.
Better would be to define a cell with a unique identifier for each one of your cases. i.e. PhotoCell, LinkCell, VideoCell, etc.
I'm trying to have two custom cells and search bar in my UIView Controller. at first I was able to do one cell and search bar and it was perfect then I added another cell and then everything became ugly.
Here is the idea of my custom cells
I get data from my server in JSON. Many shops, some of them have a design and some have no design. If a shop has a design I save the design in a variable as a string withDesign
let shop_id = subJson["id"].stringValue
var info = Shops(shopname: shopName, Logo: logoString, family_id: familiy_id , design : designImage )
self.withDesign = self.shops.filter { $0.design != "" }
self.withOut = self.shops.filter { $0.design == "" }
self.allShops = self.NofilteredArr + self.filteredArr
print(self.filteredArr)
The first cell is called design and second is called Cell
I tried multiple ways but I failed because it's my first time to deal with two cells.
What I'm tryting to do is all shops will be listed in Cell and if there is a shop that has a design then make cells with the design if no design then just list the shops. Two separate customs cells
What I'm trying to do
example of design
example of cell
Any help will be appreciated!
please Use code like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if searchActive
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
let entry1 = auxiliar?[indexPath.row]
cell.shopImage.hnk_setImage(from: URL(string: (entry1?.Logo)!))
cell.shopName.text = entry1?.shopname
return cell
}else{
if withDesign != nil
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
let entry = withDesign[indexPath.row]
cell.shopImage.hnk_setImage(from: URL(string: entry.Logo))
cell.shopName.text = entry.shopname
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "design", for: indexPath) as! DesignTableViewCell
let entry = withDesign[indexPath.row]
cell.deignImage.hnk_setImage(from: URL(string: entry.design))
return cell
}
}
I've got problems when I scroll down in my UITableview. The table shows me cells with old content when the cell is reused.
The Probleme is the following:
Swift wants to reuse an old cell, but doesn't properly clear the old content from the old cell. This leads to cells with old content, although I'm providing new data to the cells.
Architecture of the UITableView if the following:
Each custom cell has their own identifier
Each custom cell is separated in an own class
Screenshots of the problem:
Beginning of the Questionnaire Screen Shot:
The scrolled down table:
The problem here is the "Handedness"-Cell which is showing the cell number 3 (because of the reuse of the cell), which is not right
The numberOfSection-Method
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
The numberOfRowsInSection-Method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section == 0){
return questionnaireStructure.count
} else {
return 1
}
}
The cellForRowAt-Method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// first section is the normal Questionnaire
if(indexPath.section == 0){
// current questionnaireStructure
let questStruct:QuestionnaireStructure? = questionnaireStructure[indexPath.row]
// current cell is a "Headline"
if(questStruct?.elementtype == "elements/headlines"){
let cell = tableView.dequeueReusableCell(withIdentifier: "HeadlineStructureCellID", for: indexPath) as! Headline
cell.headline.text = questStruct?.headline
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else if(questStruct?.elementtype == "elements/texts"){
// current cell is a "texts"
let cell = tableView.dequeueReusableCell(withIdentifier: "TextsStructureCellID", for: indexPath) as! Texts
cell.textsLabel.text = questStruct?.text
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else if(questStruct?.questiontype == "Slider"){
// currrent cell is a "slider-Question"
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionSliderStructureCellID", for: indexPath) as! Slider
cell.sliderQuestion.text = questStruct?.question
cell.selectionStyle = UITableViewCellSelectionStyle.none
let values = (questStruct?.values)!
let valueArray = values.array as! [Values]
cell.slider.minimumValue = Float(valueArray[0].min)
cell.slider.maximumValue = Float(valueArray[0].max)
let answers = (questStruct?.answers)!
let answerArray = answers.array as! [Answers]
cell.minLabel.text = answerArray[0].label
cell.maxLabel.text = answerArray[1].label
return cell
} else if(questStruct?.questiontype == "SingleChoice"){
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionSingleChoiceStructureCellID", for: indexPath) as! SingleChoiceCell
let radioButtonController = SSRadioButtonsController()
radioButtonController.delegate = self
radioButtonController.shouldLetDeSelect = true
cell.radioButtonController = radioButtonController
cell.updateCellData(questStruct: questStruct!, indexInTable: indexPath.row)
return cell
} else if(questStruct?.questiontype == "MultipleChoice"){
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionMultipleChoiceStructureCellID", for: indexPath) as! MultipleChoiceCell
cell.multQuestionLabel.text = questStruct?.question
cell.questStruct = questStruct
return cell
} else if(questStruct?.questiontype == "YesNoSwitch"){
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionYesNoSwitchStructureCellID", for: indexPath) as! YesNoSwitch
cell.yesNoQuestion.text = questStruct?.question
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else if(questStruct?.questiontype == "TextDate"){
let cell = tableView.dequeueReusableCell(withIdentifier: "Datepicker", for: indexPath) as! DatePicker
cell.question.text = questStruct?.question
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionSingleChoiceStructureCellID", for: indexPath) as! SingleChoiceCell
//cell.singleChoiceLabel.text = questStruct?.question
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
} else {
//last section is the save button
// show the save button when the Questionnaire is loaded
if(questionnaireStructure.count != 0){
let cell = tableView.dequeueReusableCell(withIdentifier: "SaveStructureCellID", for: indexPath) as! SaveQuestionnaire
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextsStructureCellID", for: indexPath) as! Texts
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
}
}
What I checked:
the data of "questStruct" is providing the latest data
overriding the "prepareForReuse"-Methode without success
Here:
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionSingleChoiceStructureCellID", for: indexPath) as! SingleChoiceCell
//cell.singleChoiceLabel.text = questStruct?.question
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
You need to "reset" the cell in case it's being reused. Options are:
write a reset() function in the cell, to clear any assigned data and display "default" content, or
create an empty questStruct and call cell.updateCellData(questStruct: questStruct!, indexInTable: indexPath.row)
Option 1. is probably the easiest and most straight-forward.
Are you sure the data isn't actually duplicated in the questStruct array? If that's not the case then all I can think is that it looks like you have two places where a single choice cell is used. In one of them you set a bunch of data, while in the other one you don't seem to set any data. I'm talking about that last else statement where you have the part where you set singleChoiceLabel.text except it's commented out. If that condition gets hit and it's reusing a cell that was configured for the other singleChoiceStructure branch of the if condition then the information will still be filled out from the previous configuration. It's possible the questionType property of one of your QuestionnaireStructure objects is either spelled incorrectly or just a value you haven't accounted for, which is causing the if statement to hit the else which returns an unconfigured QuestionSingleChoice cell that might still have information from the last time it was used.