How to make UITableview with Textfield in swift? - ios

I want to make a table view with textfields in each cell,
I have a custom class in a swift file:
import UIKit
public class TextInputTableViewCell: UITableViewCell{
#IBOutlet weak var textField: UITextField!
public func configure(#text: String?, placeholder: String) {
textField.text = text
textField.placeholder = placeholder
textField.accessibilityValue = text
textField.accessibilityLabel = placeholder
}
}
Then in my ViewController I have
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("TextInputCell") as! TextInputTableViewCell
cell.configure(text: "", placeholder: "Enter some text!")
text = cell.textField.text
return cell
}
That works well:
But when the user enters text in the textfield and press the button I want to store the strings of each textfield in an array.
I have tried with
text = cell.textField.text
println(text)
But it prints nothing like if it was empty
How can I make it work?

In your view controller become a UITextFieldDelegate
View Controller
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var allCellsText = [String]()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.theField.delegate = self // theField is your IBOutlet UITextfield in your custom cell
cell.theField.text = "Test"
return cell
}
func textFieldDidEndEditing(textField: UITextField) {
allCellsText.append(textField.text!)
println(allCellsText)
}
}
This will always append the data from the textField to the allCellsText array.

this method is init the cell,u have not model to save this datas,so
text = cell.textfield.text
is nothing!
you can init var textString in viewcontroller,an inherit UITextFieldDelegate
optional func textFieldDidEndEditing(_ textField: UITextField)
{
textString = _textField.text
}
optional func textFieldShouldReturn(_ textField: UITextField) -> Bool{
return true
}
and cell.textField.text = textString

create a variable
var arrayTextField = [UITextField]()
after this in your func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{}
add
self.arrayTextField.append(textfield)
before returning cell, after this to display the values using
for textvalue in arrayTextField{
println(textvalue.text)
}

So here is a way to do it using the suggestion of having a textfield array. It uses the tag of the textfield to ensure it does not get added multiple times when you scroll.
// Assumes that you have a label and a textfield as a part of you tableViewCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? BodyStatsTableViewCell else {
return UITableViewCell()
}
cell.rowLabel.text = bodyTableArray[indexPath.row].rowTitle
let tagValue = indexPath.row + 100
var newRow = true
for textvalue in arrayTextField{
if textvalue.tag == tagValue {
newRow = false
}
}
if newRow {
cell.rowTextField.tag = tagValue
self.arrayTextField.append(cell.rowTextField)
cell.rowTextField.text = bodyTableArray[indexPath.row].rowValue
}
return cell
}
// And then you cam get the values when you want to save with where tag - 100 will be the array index value to update
for textvalue in arrayTextField{
print(textvalue.text)
}

Related

How to find the index of an edited textfield in a tableview

I have a UITableView, in which, each cell has UITextField embedded. I have an array of values that I want to change based on which UITextField gets edited. Currently, I am using the function:
func textFieldDidEndEditing(_ textField: UITextField) {
editedValue = textField.text!
}
But what I want to do is set a generic string, and if a user changes the text in a UITextField, then I can index the string and change that specific value. Is there a way to find the tag of the cell containing the UITextField that was edited?
in your cellForRowAtIndexPath, do this:
cell.yourTextField.tag = indexPath.row // so we are setting the tag of your textfield to indexPath.row, so that we can use this tag property to get the indexpath.
cell.yourTextField.addTarget(self, action: #selector(textChanged(textField:)), for: .editingChanged)
now in your view controller declare this function:
#objc func textChanged(textField: UITextField) {
let index = textField.tag
// this index is equal to the row of the textview
}
You can get parent cell of your textField and then find IndexPath
func textFieldDidEndEditing(_ textField: UITextField) {
if let cell = textField.superview as? UITableViewCell {
let indexpath = tableview.indexPath(for: cell)
// indexpath.row - row index, indexpath.section - section index
}
}
First define a protocol/delegate in your UITableViewCell
protocol CustomCellDelegate: class {
func getTextFeildData(cell: CustomCell, text: String)
}
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate!
func textFieldDidEndEditing(_ textField: UITextField) {
delegate.getTextFeildData(cell: self, text: textField.text ?? "")
}
}
In your cellForRowAtIndexPath function set the delegate of the cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.delegate = self
return cell
}
Then confirm the delegate method to ViewController:
extension ViewController: CustomCellDelegate {
func getTextFeildData(cell: CustomCell, text: String) {
guard let tappedIndexPath = self.tableView.indexPathForCell(cell) else {return}
print("Tapped IndexPath: \(tappedIndexPath)")
print("Text Field data: \(text)")
// update your model here
}
}

Multiple textFields in UITableView update the wrong textField when textFieldShouldReturn

I'm doing a form through a UITableView, using custom UITableViewCells which contain a UITextField each.
I'm using textFieldShouldReturn to jump to the next textField but I cannot understand why what I typed in one textField appears randomly (actually, there is weird pattern) into another textField.
Here the custom UITableViewCell
class RPTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var textField: DictionaryTextField!
#IBOutlet weak var errorLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
titleLabel.textColor = Constants.secondaryColor
textField.textColor = Constants.secondaryColor
contentView.isUserInteractionEnabled = false
errorLabel.isHidden = true
}
func setTag(tag: Int) {
textField.tag = 100 + tag
}
}
Then in my FormViewController I do
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let field = formFields?[indexPath.row] else { return UITableViewCell() }
if let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as? RPTableViewCell {
cell.titleLabel.text = field["displayText"]?.uppercased
cell.textField.text = field["userAnswer"] as? String // This was missing, but is key
cell.textField.placeholder = field["placeholder"] as? String
cell.setTag(tag: indexPath.row)
cell.textField.delegate = self
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? RPTableViewCell else { return }
tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
cell.textField.becomeFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let nextTextField = tableView.viewWithTag(textField.tag + 1) as? UITextField {
tableView.deselectRow(at: IndexPath(row: textField.tag - 100, section: 0), animated: false)
tableView.selectRow(at: IndexPath(row: textField.tag - 99, section: 0),
animated: false, scrollPosition: .middle)
nextTextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
EDIT:
In viewDidLoad I load the formFiels like this
// Read from a JSON file
guard let visitorPaths = Constants.configDict()?["visitorPaths"] as? [Dictionary<String, AnyObject>] else {
print("Error: no visitorPaths found in the configuration")
return
}
formFields = visitorPaths.first!["fields"]! as? [[String: AnyObject]]
Your are using the following snippet which does not work:
if let nextTextField = tableView.viewWithTag(textField.tag + 1) as? UITextField
The textfield is not a subview of your tableView. The Textfield is a subview of the TableViewCell.
You can acces the cell in the textFieldShouldReturn(_ textField: UITextField) delegate method like the following:
let nextIndexPath = IndexPath(row: textField.tag + 1, section: 0)
if let cell = tableView.cellForRow(at: nextIndexPath) as? RPTableViewCell {
cell.textField.becomeFirstResponder()
}
Edit for the text jumping:
Add the following textField delegate method to store the new text:
func textFieldDidEndEditing(_ textField: UITextField) {
formFields?[textField.tag - 100]["displayText"] = textField.text
}

Gather textfield text from a tableview cell (Swift)

I have a tableview with one textfield in each cell. I added a target like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customLevelCell") as! LevelTableViewCell
cell.cellTextField.addTarget(self, action: #selector(ViewController.TextfieldEditAction), for: .editingDidEnd)
return cell
}
But found out that I'm not able to use the indexpath.row / sender.tag to get the specific textfield text
#objc func TextfieldEditAction(sender: UIButton) {
}
So my question is how can I get the text after the user has edited one of the textfields.
Also how can i get the indexpath.row or sender.tag which will be used to collect the text they added to that specific textfield.
The easiest way to handle this is probably to use a delegate protocol…
In your cell
protocol LevelTableViewCellDelegate: class {
func levelTableViewCell(_ levelTableViewCell: LevelTableViewCell, didEndEditingWithText: String?)
}
class LevelTableViewCell: UITableViewCell {
#IBOutlet private weak var cellTextField: UITextField!
var delegate: LevelTableViewCellDelegate?
override func awakeFromNib() {
cellTextField.addTarget(self, action: #selector(didEndEditing(_:)), for: .editingDidEnd)
}
#objc func didEndEditing(_ sender: UITextField) {
delegate?.levelTableViewCell(self, didEndEditingWithText: sender.text)
}
}
In your view controller
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LevelTableViewCell") as! LevelTableViewCell
cell.delegate = self
return cell
}
}
extension TableViewController: LevelTableViewCellDelegate {
func levelTableViewCell(_ levelTableViewCell: LevelTableViewCell, didEndEditingWithText: String?) {
let indexPath = tableView.indexPath(for: levelTableViewCell)
// Now you have the cell, indexPath AND the string
}
Also, note that the view outlet is be private. You'll find that you write cleaner code if you follow this rule
Following is the extension of UIView that can be used to get the cell or indexPath of the cell enclosing textField
extension UIView {
var tableViewCell : UITableViewCell? {
var subviewClass = self
while !(subviewClass is UITableViewCell){
guard let view = subviewClass.superview else { return nil }
subviewClass = view
}
return subviewClass as? UITableViewCell
}
func tableViewIndexPath(_ tableView: UITableView) -> IndexPath? {
if let cell = self.tableViewCell {
return tableView.indexPath(for: cell)
}
return nil
}
}
Example :-
#objc func TextfieldEditAction(sender: UITextField) {
//replace tableView with the name of your tableView
guard let indexPath = sender.tableViewIndexPath(tableView) else {return}
}

Loop through a uitableviewcell on submit in swift 4

I am trying to access each value of a text field in a prototype cell within a UITableView on Submit. I know I should be doing this in a better way (model) but for now, I just need to access these fields and cannot find a way to do this in Swift 3/4. Would anyone be able to assist?
Code:
import UIKit
import Firebase
class FormTableViewController: UITableViewController {
var formLabels = [String]()
var formPlaceholders = [String]()
override func viewDidLoad() {
super.viewDidLoad()
FirebaseApp.configure()
formLabels = ["Name","Email","Password", "Phone"]
formPlaceholders = ["John Smith","example#email.com","Enter Password", "8585551234"]
tableView.estimatedRowHeight = 30
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return formLabels.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier:
"FormTableCell", for: indexPath)
as! FormTableViewCell
let row = indexPath.row
cell.formLabel.font =
UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
cell.formLabel.text = formLabels[row]
cell.formTextField.placeholder = formPlaceholders[row]
return cell
}
#IBAction func submitButtonPressed(_ sender: Any) {
// Need to do something with the Name, Email, Phone and Password fields here
}
}
You seem to acknowledge that updating the model directly probably makes sense. So why not do that? Just:
Have model collection for the responses;
Set up delegate for the text field in the cell;
Have cellForRowAt set that delegate; and
Make the table view controller conform to that class.
So, something quick and dirty, set up the cell to hook up editChanged event from the text field and set up protocol to inform the view controller:
protocol FormTableViewCellDelegate: class {
func fieldValueChanged(cell: UITableViewCell, textField: UITextField)
}
class FormTableViewCell: UITableViewCell {
weak var delegate: FormTableViewCellDelegate?
#IBOutlet weak var formLabel: UILabel!
#IBOutlet weak var formTextField: UITextField!
#IBAction func editingChanged(_ sender: UITextField) {
delegate?.fieldValueChanged(cell: self, textField: sender)
}
}
And then have the view controller set up model object and conform to your new protocol:
class FormTableViewController: UITableViewController {
var formLabels = [String]()
var formPlaceholders = [String]()
var values = [String?]()
override func viewDidLoad() {
super.viewDidLoad()
...
formLabels = ["Name","Email","Password", "Phone"]
formPlaceholders = ["John Smith","example#email.com","Enter Password", "8585551234"]
values = [nil, nil, nil, nil]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FormTableCell", for: indexPath) as! FormTableViewCell
let row = indexPath.row
cell.formLabel.font = .preferredFont(forTextStyle: .headline)
cell.formLabel.text = formLabels[row]
cell.formTextField.placeholder = formPlaceholders[row]
cell.formTextField.text = values[row]
cell.delegate = self // set the delegate, too
return cell
}
#IBAction func submitButtonPressed(_ sender: Any) {
print(#function, values)
}
}
// delegate protocol to update model as text fields change
extension FormTableViewController: FormTableViewCellDelegate {
func fieldValueChanged(cell: UITableViewCell, textField: UITextField) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
values[indexPath.row] = textField.text
}
}
Then that's it, your model is updated as the text fields are updated. Plus this has the advantage that it now supports cell reuse, conforms to MVC patterns, etc.
If you want to just loop through cells, you can create an array of ‘IndexPath’.
let array = (0..<formLabels.count).map { IndexPath(row: $0, section:0) }
After that you can loop over this array and access individual cell using tableview method:- tableView.cellForIndexPath
Hope this helps. (Not on my laptop, so didn’t test the syntax)

Save textField value to cell textLabel (name) [SWIFT]

I'm going to do something like this https://i.stack.imgur.com/jAGsk.png
So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file
#IBOutlet weak var inputScore: UITextField!
public func configure(text: Int?, placeholder: String) {
inputScore.text = String(text!)
inputScore.placeholder = placeholder
inputScore.accessibilityValue = String(text!)
inputScore.accessibilityLabel = placeholder
}
And here is code from the VC file
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
cell.textLabel?.text = usersIn[indexPath.row]
cell.configure(text: 100, placeholder: "Score")
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usersIn.count
}
So how to save it to the user's name?
Use DidSelectRowAtIndexPath method to get cell textLable text in textField.
Below Sample Code for That:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var btnOK: UIButton!
#IBOutlet var txtValue: UITextField!
#IBOutlet var tblData: UITableView!
let arrResult = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
tblData.dataSource = self
tblData.delegate = self
btnOK.tag = 57775
btnOK.addTarget(self, action: #selector(applyEdit(sender:)), for: .touchUpInside)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrResult.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = arrResult[indexPath.row] as? String ?? ""
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
btnOK.tag = indexPath.row
let cell: UITableViewCell = tableView.cellForRow(at: indexPath)!
txtValue.text = cell.textLabel?.text
setTitle()
}
func setTitle() {
if btnOK.tag == 57775 {
btnOK.setTitle("Add", for: .normal)
}else{
btnOK.setTitle("Update", for: .normal)
}
}
func applyEdit(sender: UIButton) {
if sender.tag == 57775 {
arrResult.add(txtValue.text ?? "")
}else{
arrResult.removeObject(at: sender.tag)
arrResult.insert(txtValue.text ?? "", at: sender.tag)
sender.tag = 57775
setTitle()
}
txtValue.text = ""
tblData.reloadData()
}
}
output:
You have to create a data model for your users:
class User: NSObject {
var points = 0
}
And then create an array of users in your view controller:
var users = [User]()
That way, you can do something like this
var user = users[indexPath.row]
user.points = 100
print(user.points) // 100
You can then display your users' points in your table view. You can also assign a tag to your text fields equal to the indexPath.row so that you can easily work with them.
In top of use user model provided by #Cesare we need to modified the cellForRowAtIndexPath method and your cell's implementation, adding a closure for data change event, and using it
#IBOutlet weak var inputScore: UITextField!
fileprivate var fnDataWasUpdated : (Int?) -> Void = {_ in} //closure for data change notification
public func configure(text: Int?, placeholder: String,_ fnListener: #escaping (Int?) -> Void) {
inputScore.text = String(text!)
inputScore.placeholder = placeholder
inputScore.accessibilityValue = String(text!)
inputScore.accessibilityLabel = placeholder
//added delegate implementation for UITextField
inputScore.delegate = self
self.fnDataWasUpdated = fnListener
}
also is needed that your cell adopts UITextFieldDelegate protocol
extension InputScoreTableViewCell : UITextFieldDelegate
{
func textFieldDidEndEditing(_ textField: UITextField)
{
if let intValue = Int(textField.text)
{
self.fnDataWasUpdated(intValue)
}
}
}
Finally we use the new closure in your cell
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
let currUser = self.users[indexPath.row]
cell.configure(text: currUser.points, placeholder: "Score",{ (newIntValue) in
currUser.points = newIntValue
})
return cell
}
This code was not tested but I had been using the main concept in several projects, so if you have any kind of problems please let me know
I hope this helps you

Resources