0

I'm new to Swift, and I can't figure out how to let users add new textFields on UIView.

For example, user taps on plus sign and 3 new textFields appear right after the previous ones. Also users can remove them all by one click at another button, which appears near the new textFields (the only simmilar system that I found is presented in standard Contacts application, where you can add new phone numbers, adresses, dates and so on).

Maybe inside of the "+" sign I should programmatically add these textFields and constraints for them, but I still can't figure out how to do it. Any suggestions?

jscs
  • 63,694
  • 13
  • 151
  • 195
Oleg Blanutsa
  • 82
  • 1
  • 6
  • You can save yourself the pain of adding constraints by using `UIStackView`. Then just add the new text fields to that. I don't know by heart how to do this but I'll have a look. This sounds fun. – Marmelador Jul 08 '17 at 15:42
  • https://stackoverflow.com/questions/1196436/uitextfield-in-uitableviewcell-adding-new-cells – Yogesh Suthar Jul 08 '17 at 15:42

1 Answers1

0

You can use UIStackView or UITableView to achieve this functionality.

To create a UITextField use the following snippet.

let tf = UITextField()
tf.borderStyle = .roundedRect
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .horizontal)
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .vertical)

Using StackView,

  1. To Add UITextField, create a TextField and add it using func insertArrangedSubview(_ view: UIView, at stackIndex: Int) method. More information can be found here.
  2. To Remove all the UITextFields, use func removeArrangedSubview(_ view: UIView) method. Here, you'll need to specify the views you want to remove. use arrangedSubviews property of UIStackView to get array of all the subviews. More information can be found here

Using UITableView,

You'll need a UITableViewCell configured to have a UITextField in it. Once you have the cell, simply keep a variable which keeps a count of all the UITextFields Every time user taps plus button, add a TextField using func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation). DO NOT FORGET TO INCREMENT YOUR COUNT. More information can be found here. You can also just Increase the count variable and reload the Table.

To Remove all, you can either use func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) or simply set the count variable as zero and use func reloadData(). More information can be found here and here

Dishant Kapadiya
  • 523
  • 4
  • 10