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?
There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.
A view that presents data using rows in a single column.
When would you choose to use a collection view rather than a table view? Suggested approach: Collection views are there to display grids, but also handle entirely custom layouts, whereas table views are simple linear lists with headers and footers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With