禁用文本字段触摸但仍接受编辑?

Make textfield touch disabled but still accept editing?

我的问题与this one相反。

我有多个文本字段,我将一个文本字段默认设置为第一响应者,但我不希望他们点击不同的文本视图并手动转到它们。我仍然希望文本字段是可编辑的。有没有办法禁止用户触摸文本字段进行编辑?

有一个选项.....试试这个...

    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
    }

是否要禁用或保留启用当前文本字段由您决定。

我忘了说你必须先设置禁用用户交互属性,然后再给每个文本字段添加标签

创建一个 UITextField subclass 并覆盖 hitTest point 方法和 return nil

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

在视图控制器中使用自定义 class。在 viewDidAppear 中,在第一个文本字段中使用 becomeFirstResponder,在 textFieldShouldReturn 方法中,移动到下一个文本字段。确保将委托设置为所有文本字段。

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
    }
}