0

My question is the opposite of this one.

I have multiple text fields and am setting one text field to be the first responder by default but I don't want them clicking on different text views and going to them manually. I still want the text fields to be editable. Is there a way to disable the user from touching a text field to edit?

Slaknation
  • 2,124
  • 3
  • 23
  • 42

2 Answers2

1

Create a UITextField subclass and override hitTest point method and return nil

class CustomTextField: UITextField {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return nil
    }
}

Use the custom class in the view controllers. In viewDidAppear use becomeFirstResponder in the first textfield, in textFieldShouldReturn method move to next textfield. Make sure to set delegate to all textfields.

class ViewController: UIViewController, UITextFieldDelegate {

    let textField1 = CustomTextField()
    let textField2 = CustomTextField()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        textField1.delegate = self
        textField1.returnKeyType = .next
        view.addSubview(textField1)

        textField2.delegate = self
        textField2.returnKeyType = .send
        view.addSubview(textField2)

        //add constraints or set frame
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textField1.becomeFirstResponder()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == textField1 {
            textField2.becomeFirstResponder()
        }
        return true
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
0

there is an option..... try this...

    func textFieldShouldReturn(_ textField: UITextField) -> Bool
    {
        // Try to find next responder
        if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
            textField.isUserInteractionEnabled = false
            nextField.isUserInteractionEnabled = true
            nextField.becomeFirstResponder()
        } else {
            // Not found, so remove keyboard.
            textField.resignFirstResponder()
        }
        // Do not add a line break
        return false
    }

Its up to you if you want to disable or leave it enable the current textfield.

I forgot to mention that you must set to disable the User interaction property first, and add tags to each textfield too

MXNMike
  • 173
  • 11