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,
- To Add UITextField, create a TextField and add it using
func insertArrangedSubview(_ view: UIView, at stackIndex: Int)
method. More information can be found here.
- 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