【问题标题】:How to call function when editing text inside of uitextfield在uitextfield中编辑文本时如何调用函数
【发布时间】:2020-07-26 18:33:49
【问题描述】:

所以我的应用中有一个登录屏幕。当用户单击登录时,会调用一个 api 来检查登录凭据是否正确(或不正确),当登录凭据不正确时会显示错误消息。现在我遇到的问题是在调用登录按钮并显示错误消息之后,我希望当用户开始更改用户名/密码字段(UITextField)中的文本时错误消息消失。起初,我尝试使用事件侦听器尝试在侦听器调用函数时将错误消息的 alpha 设置为 0.0。我使用的代码在下面。

textField.addTarget(self, action: #selector(textFieldDidChange(textfield:)), for: .editingChanged)

然后我有一个用于该操作的 objc 函数:

@objc func textFieldDidChange(textfield: UITextField) {
        errorLabel.alpha = 0.0
    }

我遇到的问题是,当用户仅单击文本字段时,错误消息就会消失。如果用户实际更改了文本字段中的文本,我只希望错误消息消失。我该怎么办?如果您还需要什么,请告诉我。

【问题讨论】:

  • 您可以使用UITextFieldDelegate,保留一个布尔值,并在此基础上在委托方法beginEditing 中隐藏错误消息。
  • 检查 textField.text 是否等于不正确的文本
  • 是的 Leo Dabus 的评论有效,但我在多个地方都遇到过这个问题,我想知道是否有更简单的方法可以做到这一点,或者我是否可以制作一些可重用的类,而不是检查输入每次的文本字段。

标签: ios swift xcode


【解决方案1】:

我写了一个快速版本的代码

解决方案是创建 2 个变量,这些变量将在您的凭据错误时存储它们的值

import UIKit

class ViewController: UIViewController {
    
 var usernameText:String? = nil
    var passwordText:String? = nil
   // we will use usernameText and PasswordText to keep track of the value of the textFields
    
    let usernameField:UITextField = {
        let textfield = UITextField()
        textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        return textfield
    }()
    let passwordField:UITextField = {
        let textfield = UITextField()
        textfield.addTarget(self, action:  #selector(textFieldDidChange), for: .editingChanged)
        return textfield
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

      @objc func loginButtonTouched(){
           if we touch your login button and the credentials are wrong {
        // you will show the errorLabel
         
        ErrorLabel.alpha = 1
        // and give value to usernameText and passwordText
        usernameText = usernameField.text
        passwordText = passwordField.text
        }else{
           present(nextVC) // for example
          }
    }

 // the username and the password textField have the same action if the text change
      @objc func textFieldDidChange(_ textfield: UITextField) {
        // now we will use the values we gave to usernameText and passwordText to check if one of them has changed their value
        if usernameText != usernameField.text || passwordText != passwordField.text {
            // if one of them changed their value we make disappear the errorLabel
            ErrorLabel.alpha = 0.0
        }
      }
        
      }





【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多