Reusing tableViewCell with UITextFields gives same data from an Array - ios

I am having a section with custom tableViewCell and this cell has two text fields.
This cell is used to display phone number of a user - country code in one text field and the number in other text field.
I fetch data from a service and if the user has more than one phone, based on the count of the phones, I am updating numberOfRowsInSection and cellForRowAtIndexPath. I do not have any issue till here.
For example, if user has two phones, I return 2 in numberOfRowsInSection, and shows two cells (same custom cell with two textFields).
The Problem:
I get the same data - the second phone number details - in both the cells. But I need to have list of phone numbers displayed one after the other in my custom cell textfields.
Here is my code:
numberOfRowsInSection
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 3:
return (user.phones?.count)!
default:
return 1
}
}
cellForRowAtIndexPath
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
case .ContactPhones:
if contactCellExpanded == true {
cell = tableView.dequeueReusableCellWithIdentifier("PhoneCell") as? PhoneCell
}
case .ContactEmail:
if contactCellExpanded == true {
cell = tableView.dequeueReusableCellWithIdentifier("EmailCell") as? EmailCell
}
default:
break
}
PhoneCell
import UIKit
class PhoneCell: ProfileCell {
#IBOutlet weak var countryCode: UITextField!
#IBOutlet weak var addPhoneButton: UIButton!
#IBOutlet weak var teleNumber: UITextField!
#IBAction func addPhoneButtonAction(sender: AnyObject) {
}
override func configure(withUser user: XtraUser, language: String, indexPath: NSIndexPath) {
super.configure(withUser: user, language: language, indexPath: indexPath)
self.countryCode.borderStyle = .RoundedRect
self.teleNumber.borderStyle = .RoundedRect
if let userPhoneInfo = user.phones {
for i in 0..<userPhoneInfo.count {
print ("numbers \(userPhoneInfo[i].number)")
self.countryCode.text = userPhoneInfo[i].country
self.teleNumber.text = userPhoneInfo[i].number
}
}
}
}
I understand that I am using a for loop to get the numbers list when available, but how do I assign each value to the cell's textField?
Please Help!
Thanks in Advance

Since in configure method you know the index path of the cell why dont you just use
override func configure(withUser user: XtraUser, language: String, indexPath: NSIndexPath) {
super.configure(withUser: user, language: language, indexPath: indexPath)
self.countryCode.borderStyle = .RoundedRect
self.teleNumber.borderStyle = .RoundedRect
print("Enumerated \(user.phones?.enumerate())")
if let userPhoneInfo = user.phones {
self.countryCode.text = userPhoneInfo[indexPath.row].country
self.teleNumber.text = userPhoneInfo[indexPath.row].number
}
}
But anyway the best solution is to have model for each cell and pass it to this configure method.

Wrong logic implementation in numberOfRows method.
In that method set number of rows according to your data in response.

Related

UITableViewCell dequeuereusablecellwithidentifier returns the same cell

I am creating a UITableView that enables the user to add a variable amount of data. Table looks like this initially:
When the user clicks on the "+" button, i would like to add a new cell with a UITextField for entering data. This new cell is a Custom UITableViewCell called "RecordValueCell". Here's what is looks like:
//Custom UITableViewCell
class RecordValueCell : UITableViewCell {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var deleteButton: UIButton!
var onButtonTapped : ((_ sender : UIButton)->Void)?
#IBAction func deleteButtonTouched(_ sender: Any) {
guard let senderButton = sender as? UIButton else {
return
}
onButtonTapped?(senderButton)
}
}
However when i try to add another cell, using the tableView.dequeueReusableCell(withIdentifier: ) function, it seems to return the same cell. And here is what my UI looks like:
Empty space at the top of the section where my new cell should be. Here is the code to add the cell:
func addNewValueCell() {
guard let reusableValueCell = self.tableView.dequeueReusableCell(withIdentifier: "valueCell") as? RecordValueCell else {
fatalError("failed to get reusable cell valueCell")
}
var cell = Cell() //some custom cell Object
//add the gray horizontal line you see in the pictures
reusableValueCell.textField.addBorder(toSide: .Bottom, withColor: UIColor.gray.cgColor, andThickness: 0.5)
reusableValueCell.onButtonTapped = { (sender) in
self.removeValue(sender: sender)
}
cell.cell = reusableValueCell
self.sections[self.sections.count - 1].cells.insert(cell, at: 0)
//When i put a break point at this spot, i find that reusableValueCell is the same object as the cell that is already being used.
tableView.reloadData()
reusableValueCell.prepareForReuse()
}
When i debug it, i find that dequeueReusableCell(withIdentifier: ) returns the exact same RecordValueCell multiple times.
Here is my cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.sections[indexPath.section].cells[indexPath.row].cell else {
fatalError("error getting cell")
}
return cell
}
numberOfRowsInSection
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sections[section].cells.count
}
First of all, you will need to set the View Controller Class that this table is contained in as the table's UITableViewDataSource
tableView.dataSource = self // view controller that contains the tableView
Create an array of strings as member of your View Controller class which contains the data for each cell:
var strings = [String]()
Then you will need to implement the following method for the UITableViewDataSource protocol:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return strings.count
}
You should also be dequeueing the cells in your cellForRowAt method like so:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: yourIdentifier) as! YourCellClass
cell.textLabel = strings[indexPath.row]
return cell
}
Then whenever the user enters into the textField, their input will be appended to this array:
let input = textField.text
strings.append(input)
tableView.reloadData()
Once the data is reloaded, the cell will be added to the table automatically since the number of rows are defined by the String array's length and the label is set in the cellForRowAt method.
This feature is very easy to implement if you will do in a good way.
First, you have to create two TableCell. First to give the option to add a record with plus button and second for entering a value with textfield. Now always return first cell (AddRecordTableCell) in the last row in tableView, and return the number of rows according to entered values like
return totalValues.count + 1

UITableView Duplicate cells (custom cells with textfields)

I have spent days on resolving this issue and after trying much I am asking a question here. I am using a custom UITableViewCell and that cell contains UITextFields. On adding new cells to the table view, the table view behaves abnormal like it duplicates the cell and when I try to edit the textfield of new cell, the textfield of previous cel gets edited too.
The behavior of duplication is as follows: 1st cell is duplicated for 3rd cell. I don't know this is due to reusability of cells but could anyone tell me about the efficient solution?
I am attaching the screenshot of UITableViewCell.
The code for cellForRow is as follows:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : Product_PriceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "product_priceCell") as! Product_PriceTableViewCell
cell.dropDownViewProducts.index = indexPath.row
cell.txtDescription.index = indexPath.row
cell.tfPrice.index = indexPath.row
cell.dropDownQty.index = indexPath.row
cell.tfTotalPrice_Euro.index = indexPath.row
cell.tfTotalPrice_IDR.index = indexPath.row
cell.dropDownViewTotalDiscount.index = indexPath.row
cell.dropDownViewDeposit.index = indexPath.row
cell.tfTotalDeposit_Euro.index = indexPath.row
cell.tfRemaingAfterDeposit_IDR.index = indexPath.row
return cell
}
The issue is the cell is being reused by the UITableView, which is what you want to happen for good scrolling performance.
You should update the data source that supports each row in the table to hold the text the user inputs in the field.
Then have the text field's text property assigned from your data source in cellForRowAt.
In other words, the UITableViewCell is the same instance each time you see it on the screen, and so is the UITextField and therefore so is it's text property. Which means it needs to be assigned it's correct text value each time cellForRowAt is called.
I'm unsure of your code so I have provided an example of how I would do something like what you want:
class MyCell: UITableViewCell {
#IBOutlet weak var inputField: UITextField!
}
class ViewController: UIViewController {
#IBOutlet weak var table: UITableView!
var items = [String]()
fileprivate func setupItems() {
items = ["Duck",
"Cow",
"Deer",
"Potato"
]
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupItems()
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// the # of rows will equal the # of items
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// we use the cell's indexPath.row to
// to get the item in the array's text
// and use it as the cell's input field text
guard let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? MyCell else {
return UITableViewCell()
}
// now even if the cell is the same instance
// it's field's text is assigned each time
cell.inputField.text = items[indexPath.row]
// Use the tag on UITextField
// to track the indexPath.row that
// it's current being presented for
cell.inputField.tag = indexPath.row
// become the field's delegate
cell.inputField.delegate = self
return cell
}
}
extension ViewController: UITextFieldDelegate {
// or whatever method(s) matches the app's
// input style for this view
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else {
return // nothing to update
}
// use the field's tag
// to update the correct element
items[textField.tag] = text
}
}
I suggest to do the following
class Product_PriceTableViewCell: UITableViewCell {
var indexRow: Int = -1
func configureCell(index: Int) {
cell.dropDownViewProducts.clean()
...
cell.tfRemaingAfterDeposit_IDR.clean()
}
}
where clean is the function to empty de view (depend on the type)
Then in the delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : Product_PriceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "product_priceCell") as! Product_PriceTableViewCell
cell.configureCell(row: indexPath.row)
return cell
}
As #thefredelement pointed out when the cell is not in the view frame, it is not created. Only when the view is going to appear, it tries to reuse an instance of the cell and as the first is available, the table view uses it but does not reinitialize it. So you have to make sure to clean the data
The rest of the answer is for better coding.

UILabel Not Changing Text

I have created an array in a tableView to record how many cells have checkmarks or not, and tried to have the Label text change based on how many checkmarks there are.
My code:
#IBOutlet weak var myLabel: UILabel!
func setText() {
if checkmarks == [0: false] {
self.myLabel.text = "text"
}
if checkmarks == [1: false] {
self.myLabel.text = "text1"
}
}
I am not getting any errors, but the text is not changing. Any advice is appreciated.
UPDATE: The array I am trying to take values from is in another class.
Here is that code:
var checkmarks = [Int: Bool]()
the checkmarks get saved so I thought by writing the above code in a (public class??), my other class files could access it.
Perhaps I need to call checkmarks at the start of the other class file too? Edit: That is an invalid redeclaration my bad.
Thanks for the help
UPDATE 2: The problem was in the interpretation of the array system. I rewrote my code as a loop (which I will add on request) and that fixed it. Thank you all for helping!!
as of my understanding you are trying to show the selected row with tick mark in a tableview, so if it then there is another approach to show it.
consider the following approach.
declare your variables as global to class
var selected = [String]()
let colors = ["Apple","Pear", "Banana","Orange",]
and your datasource and delegate methods should like similar to this
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.selectionStyle = .none
if selected.contains(colors[indexPath.row]) {
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
cell.textLabel?.text = colors[indexPath.row]
return cell;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return colors.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selected.contains(colors[indexPath.row]) {
selected.remove(at: selected.index(of: colors[indexPath.row])!)
}else{
selected.append(colors[indexPath.row])
}
tableView.reloadData()
}
}
and finally your output will be like this

How to hide cell if "active" column is "no" in Swift 3/Xcode 8

I'm just in the process of putting a prototype app together in Swift 3.0.
At the minute, all API information is Parsed in to table cells. What I was hoping to do was introduce the facility where if I set an "Active" column in my database to "no" then how could I prevent that cell from showing in the table view?
Currently the code is this:
func configure(offence: Offence) {
if let name = offence.name, let act = offence.act {
self.textLabel?.text = name
self.detailTextLabel?.text = act
}
I've tried playing around with if/else statements but I'm not having much luck.
if your Offences have an active property you can use it to filter your server response and only show those with the active property set to true. something like this:
struct Offence {
var name: String
var active: Bool
}
class YourViewController: UITableViewController {
// all the offences you get from the server
let offences: [Offence] = []
// only the active offences - use those as your datasource!
var visibleOffences: [Offence] {
return offences.filter { $0.active }
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return visibleOffences.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YourCell", for: indexPath)
cell.textLabel?.text = visibleOffences[indexPath.row].name
return cell
}
}

Some table view cells become invisible after I added more cells. Why?

I am using a variation of the technique mentioned in this post to add and remove table view cells dynamically.
Initially, the table view cells looks like this:
Then, I add a new cell to section 1. Section 1 is the section above the "RESULTS" section. So I expect the new cell to appear below the cell with the name "h". But no! It turns into this!
The new cell is added in section 2 (The "RESULTS" section) and is added below the cell with the name "b". What's even more surprising is that the second cell in section 2 has disappeared!
Here is how I add the cell:
I have an array of cells here:
var cells: [[UITableViewCell]] = [[], [], []]
each subarray in the array represents a section. In viewDidLoad, I added some cells to sections 0 to 2 by calling:
addCellToSection(1, cell: someCell)
addCellToSection is defined as
func addCellToSection(section: Int, cell: UITableViewCell) {
cells[section].append(cell)
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: cells[section].endIndex - 1, inSection: section)], withRowAnimation: .Top)
}
And the table view data source methods are defined in the same way as the aforementioned post.
I tried to print the number of cells in each section when I add the cell:
print("no. of rows in section 1: \(self.tableView(tableView, numberOfRowsInSection: 1))")
print("no. of rows in section 2: \(self.tableView(tableView, numberOfRowsInSection: 2))")
And the printed values are consistent i.e. when I add a new cell, the no. of rows increase by 1. But the weird thing is that it keeps placing rows in the wrong position.
Extra info: how I create the cell:
I first dequeue the cells from the prototype cells. I then call viewWithTag to get the text fields that are in the cell and add them to a [(UITextField, UITextField)]. Don't know whether this matters.
Okay so first of all, you should never store UITableView cells in some custom collection. This is and should be done by iOS, not you.
The data you are using to populate the cells are stored in some model I presume?
Your tableView should register cells using either:
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String)
or
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String)
or using Prototype cells in the Xib/Storyboard.
I recommend this setup, or similar:
class MyModel {
/* holds data displayed in cell */
var name: String?
var formula: String?
init(name: String, formula: String) {
self.name = name
self.formula = formula
}
}
class MyCustomCell: UITableViewCell, UITextFieldDelegate {
static var nibName = "MyCustomCell"
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var formulaTextField: UITextField!
weak var model: MyModel?
override func awakeFromNib() {
super.awakeFromNib()
nameTextField.delegate = self
formulaTextField.delegate = self
}
func updateWithModel(model: MyModel) {
/* update labels, images etc in this cell with data from model */
nameTextField.text = model.name
formulaTextField.text = model.formula
self.model = model
}
/* This code only works if MyModel is a class, because classes uses reference type, and the value
of the name and formula properies are changed in the model stored in the dictionary */
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
let newText = textField.text
switch textField {
case nameTextField:
model?.name = newText
case formulaTextField:
model?.formula = newText
default:
print("Needed by compiler..")
}
}
}
class MyController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableVieW: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
/* This is not needed if you are using prototype cells in the Xib or Storyboard.
Convenient to use nib name as cell identifier */
tableVieW.registerNib(UINib(nibName: MyCustomCell.nibName, bundle: nil), forCellReuseIdentifier: MyCustomCell.nibName)
tableVieW.delegate = self
tableVieW.dataSource = self
}
private var dictionaryWithModelsForSection: Dictionary<Int, [MyModel]>!
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let sectionCount = dictionaryWithModelsForSection.keys.count
return sectionCount
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let models: [MyModel] = modelsForSection(section) else {
return 0
}
let rowCount = models.count
return rowCount
}
private func modelsForSection(section: Int) -> [MyModel]? {
guard section < dictionaryWithModelsForSection.count else {
return nil
}
let models = dictionaryWithModelsForSection[section]
return models
}
private func modelAtIndexPath(indexPath: NSIndexPath) -> MyModel? {
guard let models = modelsForSection(indexPath.section) where models.count > indexPath.row else {
return nil
}
let model = models[indexPath.row]
return model
}
func addRowAtIndexPath(indexPath: NSIndexPath, withModel model: MyModel) {
add(model: model, atIndexPath: indexPath)
tableVieW.insertRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
private func add(model model: MyModel, atIndexPath indexPath: NSIndexPath) {
guard var models = modelsForSection(indexPath.section) where indexPath.row <= models.count else { return }
models.insert(model, atIndex: indexPath.row)
dictionaryWithModelsForSection[indexPath.section] = models
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MyCustomCell.nibName, forIndexPath: indexPath)
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let
cell = cell as? MyCustomCell,
model = modelAtIndexPath(indexPath) else { return }
cell.updateWithModel(model)
}
}
If you want to insert a cell you can use the method addRowAtIndexPath:withModel i wrote in MyController above, you need to call that from some function creating the corresponding model...

Resources