iOS Swift - Export Data from Custom Table View Cells on Exit/Save - ios

I have a UITableView with 5 custom UITableViewCells. In the custom UITableViewCells I have IBOutlets for my UI-elements (UILabel, UITextField). I cannot create IBOutlets for the UI-elements in my view controller because they are already linked to my custom UITableViewCells.
I want to be able to access the data in my UITableViewCells when the UIBarButtonItem of type "Save" is pressed. In order to parse the data from my UITableViewCells to my own class.
I have already written the unwind method in the return controller, and have written the prepareForSegue method in the source controller, got that working. I only need to retrieve the data from the custom UITableViewCells at that specific time (on save, not on finished editing textfield or when a table row has been dis-selected).
What would be the "best practice" to achieve this kind of behaviour?

Since I don't know what your custom cells look like, I'll just use a cell that has a single text field in it (named myTextField) as an example.
In the custom cell class, add a property like this:
var value: String? {
return myTextField.text
}
And in the save button's #IBAction method, do this:
var data = [String]()
let sections = numberOfSectionsInTableView(self.tableView)
for s in 0..<sections {
let rows = tableView(self.tableView, numberOfRowsInSection: s)
for r in 0..<rows {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: r, inSection: s)) as! YourCustomCell
data.append(cell.value)
}
}
And now you have an array of strings!
If your cell's data is not as simple as a string, please consider using Eureka.

Related

using a Struct to change tableViewCell from TableViewController

In my app's chat feature, I use a UITableView to present chat history.
Cells are subclasses of UITableViewCell. The class receives a Chat object that contains all the info it needs to build the cell.
I have a Firebase listener that fires when the "last message" is changed. It changes a UILabel text to "new Message!" and then a protocol/delegate reloads the table view. Now I need to change the label back to "".
When the user clicks the cell, I use didSelectRowAt to segue to JSQMessagesViewController after preparing for segue. My idea is to use prepare for segue or even didSelectRowAt itself to change a Boolean variable in the UITableViewCell that corresponds to that chat Object. Navigating back to the tableViewController will trigger reloadData.
Each ChatObject has a unique ID that I can access. After firing the listener, I will set this Boolean to one value. After clicking the cell, I will set it to another. the state of the variable will tell the IBOutlet what text to show. In the UITableViewCell class, I use:
var chat: Chat! {
didSet {
self.updateUI()
}
}
}
So in self.updateUI() I make necessary changes, but can I make properties in the UITableViewCell mutable/visible from the UITableViewController?
How can I make properties in the UITableViewCell that are mutable from the UITableViewController
You don't. You make changes in your model and tell the table view to reload its data.
So in self.updateUI() I make necessary changes, but can I make properties in the UITableViewCell mutable from the UITableViewController?
I don't think you're trying to do what you say you are. In the case that you are trying to access the properties of your custom UITableViewCell subclass, you might want to use cellForRowAtIndexPath(). Then cast the result to whatever class name you have for your UITableViewCell subclass.
Example:
If I want to change the 5th row outside of our table view dataSource, I could do something like this.
let fifthIndexPath = IndexPath(row: 5, section: 0)
let thisCell = myTableView.cellForRowAtIndexPath(at indexPath: fifthIndexPath) as! MyCustomTableViewCell
thisCell.property = value
See:
https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614861-tableview

Create an array for each collection view cell

I am trying to create a collection view with custom collection view cells.
I want to keep track of the number of times each cell is tapped and store in an array. So, my custom cell has a label, IBAction and an array.
I am able to do this by appending 1 to the array inside IBAction and printing out the count.
However, I want to access this data outside the custom cell view class. I want to have an array specific to each cell i.e. by the name
self.titleLabel.text!
Of course, I can't use a variable for the name of an array! (I wish I could)
How do I store data in such case?
Where and how do I need to define the array to easily store and process data?
You may declare Dictionary that holds tap count in your UIViewController:
var tapCounts = [NSIndexPath: Int]()
let collectionView = UICollectionView()
func tapAction(sender: UICollectionViewCell) {
if let indexPath = collectionView.indexPathForCell(sender) {
tapCounts[indexPath] = (tapCounts[indexPath] ?? 0) + 1
}
}

Swift 2.0, UITableView: cellForRowAtIndexPath returning nil for non-visible cells

Please don't mark this as a duplicate question because I have found no suitable answer for my query.
I have a table view with cells that contain text fields. I have a button at the bottom of the screen. The number of rows is greater than the screen can display, so some cells are not in view. I want that at any point when the button is pressed, all textfields be read and the text input be processed. I am unable to do so because apparently because of the reusability of cells, cells out of view do not exist at all and cellForRowAtIndexPath for those indexPaths gives a runtime error. I have read answers that say that this simply can't be done. But I find it hard to believe that there is no workaround to this. Please help. Thanks in advance!
This definitely can't shouldn't be done (accessing cells that are off screen, or implementing workarounds to allow it), for reasons of (at least) performance and memory usage.
Having said that there is, as you put it, a workaround. What you will need to do it change how you are storing the values in those text fields. Rather than iterating through cells and retrieving the text directly from the text fields you should store the text for each field in an collection.
Define a dictionary property on your table view controller / data source to hold the text for each row.
Act as the delegate of UITextField and assign as such in tableView:cellForRowAtIndexPath:
Implement textField:didEndEditing: (or whatever is appropriate for your use case) and store the text in the dictionary keyed against the index path relating to the cell that contains that text field.
Update the button action method to use this dictionary instead of iterating through cells.
Create a UITableViewCell subclass, add your tableViewCells a index property and introduce a delegate like:
protocol CustomCellDelegate {
func didEditTextField(test : String, atIndex : Int)
}
Create a delegate variable on your UITableViewCell subclass.
var delegate : CustomCellDelegate?
Implement the UITextViewDelegate in your tableViewCell and set the cell to be the delegate of your textfield.
Implement these two methods:
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField : UITextField) {
// call back with the delegate here
// delegate?.didEditTextField(textfield.text, atIndex: self.index)
}
So when the user ends editing the textField, your cell will call out with a delegate, sending the text and the index.
On your viewController, when you init your tableViewCell, set the delegate of the cell to the viewController, and set the index to indexPath.row .
Set up on your viewController a String array with as many items as many tableViewCells you got. Init the array with empty strings.
So you got the delegate on your viewController, and whenever it is called, you just insert the returned text to right index in the string array on your viewcontroller.
What do think, will this work?
If we can assume that cells that have NEVER been created has no text inputs, then create an Array or Set ourselves and clone the content/input texts there whenever user inputs to a cell's textfield.
Whenever, that button is clicked, you can iterate the array instead of cells to get all the inputs.
This is a bit hacky though..

Call UITableViewCell Method from Method in main VC?

I'm trying to do the opposite of what most people on this topic are asking to do. Most people want a button within a table view cell to call a method in their VC / VC table. I already have a protocol doing that.
Problem / Question
What I am trying to add now is the opposite: I need a button press on my main ViewController (which houses my table) to call a method within my CusomTableViewCell class (note: the button pressed on the main VC is not in the table). I have the protocol class created and the function written, but I don't know how to set the CustomCellViewClass as the delegate. When I did the opposite, I inserted "cell.delegate = self" into the cellForRowAtIndexPath method. I've also used prepareForSegue to assign a delegate. But with no segue and now cell-creation-method, I'm lost!
Example of Desired Function
My end goal is that pressing a button that is in the main VC will change the title of a button within the cells. A simple example would be that I have one view with a single table, on button press the table contents switch between two arrays, cars and motorcycles. When the table is showing cars, the cell button titles should all read "Look inside" but when showing the motorcycle button it should read "Look closer".
Code
I've already written the function that I want the cell to execute:
func cellButton_Title_Switch (currentList: String) {
if vcState == "cars" {
cellButton.setTitle("Look inside", forState: UIControlState.Normal)
}
else {
cellButton.setTitle("Look closer", forState: UIControlState.Normal)
}
}
I created the protocol:
protocol delegateToChangeCellBut {
func cellButton_Title_Switch (currentList: String)
}
I have the self.delegate.cellButton_Title_Switch(currentList) within my VC button and the protocol added to my custom cell class declaration. But how do I do that last missing piece in the custom cell class, where I assign the class to the delegate?
My original problem was that my UITableView's cell has buttons and labels, some of which change to match the state of things outside the table, things handled by the mainViewController.
The custom cell is defined by a customCellviewController. All the custom cell buttons and labels have their IBOutlets connected to the customCellviewController. I couldn't figure out how to make an action/change outside the table (in the mainViewController) immediately cause the cell labels and buttons to change.
Note: Protocols tend to work they other way around (a cell action triggers a function in the mainVC). I couldn't figure out how to use a protocol to solve this. Luckily, the solution was much simpler than a protocol.
The Solution!
I wrote the "updateCell" method that would change the labels and buttons and that code now sits in the customCellviewController. Then I called/triggered the "updateCell" function from the mainViewController simply by adding the call into my cellForRowAtIndexPath function. So it looks something like this:
var stateOfPage = "Green"
//Creates the individual cells. If the above function returns 3, this runs 3 times
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Setup variables
let cellIdentifier = "BasicCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! customCell
cell.updateCell(stateOfPage)
return cell
}
Now the above code/method runs when the table gets built. So to update the cells, have some button tap or other action reload the table data:
tableView.reloadData()
Good luck.

Pass table cells textlabel data to array in swift

I want to pass table cell's textLabel data of UITableViewController to NSArray. Those cell have identifier name Cells and accessory type checkmark
Code that does exactly what you asked is here:
func getCellsData() -> [String] {
var dataArray: [String] = []
for section in 0 ..< self.tableView.numberOfSections() {
for row in 0 ..< self.tableView.numberOfRowsInSection(section) {
let indexPath = NSIndexPath(forRow: row, inSection: section)
let cell = self.tableView.cellForRowAtIndexPath(indexPath)!
if cell.reuseIdentifier == "Cells" && cell.accessoryType == UITableViewCellAccessoryType.Checkmark {
dataArray.append(cell.textLabel!.text!)
}
}
}
return dataArray
}
But I would like to recommend you find different approach, because this is the rude traverse of tableView. You probably have your dataSource model that can give you ll data you need. Additionally, this code doesn't check for errors, for example if there is no text in cell at some indexPath
Two things I'd advise.
First, looks like you're using the checkmark accessory to indicate multiple selections. It's really intended for single selection, like a radio button. Better to use the allowMultipleSelectionsoption on the tableview. This will allow...
...the second thing. Copying text from cells into an array is the wrong way round to do it. Better to ask the table view and call it's - (NSArray *)indexPathsForSelectedRows this will give you an array of index paths to selected cells then you can ask for each cell and grab any data you want from it. This gives you better live data and prevents you unknowingly creating a circular reference from the view controller of the tableview and the content in the tableview cells.

Resources