Reputation: 109
I want to have a table view, where you can add a new element when you click on the last cell. I can't find out, how I save whats put in the textfield, after you click "ok".
As you can probably see from my code, I'm very new to programming and it is likely way to complicated. It would be super cool, if someone could help me out.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var companyTableView: UITableView!
var psgTextField: UITextField?
var emTextField: UITextField?
var passengers = [""]
var button: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
configureButton()
companyTableView.delegate = self
companyTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return passengers.count
}
@objc func buttonTapped(sender: UITapGestureRecognizer) {
let alertController = UIAlertController(title: "Enter name and email",
message: nil,
preferredStyle: .alert)
alertController.addTextField(configurationHandler: psgTextField)
alertController.addTextField(configurationHandler: emTextField)
let okAction = UIAlertAction(title: "Submit", style: .default, handler: self.okHandler)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true)
}
func psgTextField(textField: UITextField!) {
psgTextField = textField
psgTextField?.placeholder = "Name"
}
func emTextField(textField: UITextField!) {
emTextField = textField
emTextField?.placeholder = "Email"
}
func okHandler(alert: UIAlertAction!) {
let psgStr = (psgTextField?.text)!
passengers.removeLast()
passengers.append(psgStr)
passengers.append("")
}
func configureButton() {
button = UILabel()
let frame = CGRect(x: 0, y: 5, width: 300, height: 30)
button?.frame = frame
button?.text = " Add Passenger"
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonTapped(sender:)))
button?.addGestureRecognizer(tapGesture)
button?.isUserInteractionEnabled = true
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let passenger = passengers[indexPath.row]
if let cell = companyTableView.dequeueReusableCell(withIdentifier: "cell") {
cell.textLabel?.text = passenger
if cell.textLabel?.text == "" {
cell.contentView.addSubview(button!)
} else {
// Nothing
}
return cell
}
return UITableViewCell()
}
}
When I now click on "Submit", the alert just goes of and nothing changed.
Upvotes: 0
Views: 60
Reputation: 303
You need to call companyTableView.reloadData()
in your okHandler
method.
Upvotes: 1