如何同时检查textField和textView中的相同条件?

时间:2019-06-06 05:48:05

标签: ios swift xcode uitextfield uitextview

我有2个textFields和1个textView,所有这些字段都有一个内容,来自previousViewController,如果新内容与以下内容不同,我需要根据用户在这些字段中的更改启用或禁用rightBarButtonItem当前内容,来自previousViewController。如何同时检查textFields和textView?现在我有了(条件有时彼此矛盾)

在viewDidLoad中:

loginTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

displayNameTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

然后:

@objc func textFieldDidChange(_ textField: UITextField) {

    if displayNameTextField.text != currentDisplayName || loginTextField.text != currentUsername {
        self.navigationItem.rightBarButtonItem?.isEnabled = true
    } else {
        self.navigationItem.rightBarButtonItem?.isEnabled = false
    }

}

func textViewDidChangeSelection(_ textView: UITextView) {
    if aboutTextView.text == currentAbout {
        self.navigationItem.rightBarButtonItem?.isEnabled = false
    } else {
        self.navigationItem.rightBarButtonItem?.isEnabled = true
    }
}

1 个答案:

答案 0 :(得分:1)

为什么不将其提取到函数中并像这样检查它:

@objc func textFieldDidChange(_ textField: UITextField) {
    validateFields()
}

func textViewDidChangeSelection(_ textView: UITextView) {
    validateFields()
}

func validateFields() {
    if aboutTextView.text == currentAbout || displayNameTextField.text == currentDisplayName || loginTextField.text == currentUsername {
        self.navigationItem.rightBarButtonItem?.isEnabled = false
    } else {
        self.navigationItem.rightBarButtonItem?.isEnabled = true
    }
}