skip to Main Content

I have already put the button and textfield on the storyboard.
I want to put a new textfield under it with code, but I don’t know how.
Do you have a better way?
xcode12.2

@IBOutlet weak var kgTextField1: UITextField!
    @IBOutlet weak var repTextField1: UITextField!
    @IBOutlet weak var repTextField2: UITextField!
    @IBOutlet weak var repTextField3: UITextField!
    
    var addKgTextField : UITextField = UITextField()
override func viewDidLoad() {
        super.viewDidLoad()
addKgTextField.frame = CGRect(x: 20, y: 100, width: 60, height: 34)
    }
@IBAction func didTapAddSetButton(_ sender: Any) {
        self.view.addSubview(addKgTextField)
        self.view.reloadInputViews()
    }

2

Answers


  1. This code solve your problem.

    private var textFiled : UITextField{
        let field = UITextField()
        field.placeholder = "Email Address..."
        field.returnKeyType = .next
        field.leftViewMode = .always
        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))
        field.autocapitalizationType = .none
        field.autocorrectionType = .no
        field.layer.masksToBounds = true
        field.layer.cornerRadius = Constants.cornerRadius
        field.backgroundColor = .secondarySystemBackground
        field.layer.borderWidth = 1.0
        field.layer.borderColor = UIColor.secondaryLabel.cgColor
        return field
    }
    
    var lastTextFiledFrame: CGFloat = CGFloat.zero
    
    @IBAction func didTapAddSetButton(_ sender: Any) {
        let newTextFiled = self.textFiled
        view.addSubview(newTextFiled)
        newTextFiled.frame = CGRect(x: 20, y: registerButton.bottom+10 + self.lastTextFiledFrame, width: view.width-40, height: 52)
        self.lastTextFiledFrame += newTextFiled.frame.height + 10
    }
    
    Login or Signup to reply.
  2. You could also add another Textfield and change its visibility when the button is pressed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search