我有4个文本字段,一个按钮和一个图像,我想要实现的是,当按下按钮时,它应该警告用户有空的文本字段并显示指向空文本字段的图像,但是使用户将文本放入空白文本字段时,图像消失。谢谢

这是我的功能

func checkFields(){
    let userEmail = user_EmailTxtField.text!
    let userPassword = user_PassTxtField.text!
    let passwordConfirm = pass_ConfirmTxtField.text!
    let userPhone = user_PhoneTxtField.text!
    //Set backArrow image to show input error to password
    let imageName = "backArrow.png"
    let image = UIImage(named: imageName)
    let passImageView1 = UIImageView(image: image!)
    passImageView1.frame = CGRect(x: 319, y: 331, width: 49, height: 49)
    view.addSubview(passImageView1)
    //Show Arrow image to password confirm error
    let passConfirmImageView1 = UIImageView(image: image!)
    passConfirmImageView1.frame = CGRect(x: 319, y: 394, width: 49, height: 49)
    view.addSubview(passConfirmImageView1)
    //Show arrow Image to email error
    let emailImageView1 = UIImageView(image: image!)
    emailImageView1.frame = CGRect(x: 319, y: 270, width: 49, height: 49)
    view.addSubview(emailImageView1)
    //Set image to phonetxt field error
    let phoneImageView1 = UIImageView(image: image!)
    phoneImageView1.frame = CGRect(x: 319, y: 209, width: 49, height: 49)
    view.addSubview(phoneImageView1)
    if userPhone.isEmpty {
        phoneImageView1.isHidden = false
    } else {
        phoneImageView1.isHidden = true
    }
    if userEmail.isEmpty {
        emailImageView1.isHidden = false
    }
    if userPassword.isEmpty {
        passImageView1.isHidden = false
    }
    if passwordConfirm.isEmpty {
        passConfirmImageView1.isHidden = false
    }
}

最佳答案

您可以调用一个函数来处理检查,然后在文本不为空的情况下隐藏图像,如下所示:

1在为事件.editingChanged创建textField的位置将一个目标添加到textField中:

user_EmailTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
user_PhoneTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
pass_ConfirmTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
pass_ConfirmTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)


2设置用于检查文本字段是否被编辑的方法:

func textFieldDidChange() {
  emailImageView1.isHidden = user_EmailTxtField.hasText
  phoneImageView1.isHidden = user_PhoneTxtField.hasText
  passImageView1.isHidden = pass_ConfirmTxtField.hasText
  passConfirmImageView1.isHidden = pass_ConfirmTxtField.hasText
}


因此,如果将此示例应用于所有文本字段,则无需在checkFields()中进行检查,并且可以将方法重命名为setupTextFields(),例如,仅将其用于创建文本字段

在类的所有方法中使用图像视图的示例,但请确保在viewDidLoad()中进行初始化,例如,以避免在展开可选值时发现nil错误

class YourClass: UIViewController {

  // ImageView Reference
  var emailImageView1: UIImageView!

  // then your checkFields method
  func checkFields() {
    // code before
    emailImageView1 = UIImageView(image: image!)
    // code after
  }
}

10-08 05:30
查看更多