如何访问函数变量并将其从 superview 中删除?

How to access function variable and remove it from superview?

我创建了一个函数,如果您键入超过四个字符,textField 会在角落显示一个带有绿色勾号的图像,但是当我删除 textField 中的所有字符时,它会显示一条错误消息,但我想删除那个绿色勾号图像。我试过了

.removeFromSuperView

但是没用。

我很难从函数访问变量以将其从 superview 中删除。

这是我在文本字段中创建图像的代码(最右)

func addRightImage(txtField: UITextField, andImage img:UIImage)
{
    let rightImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height))

    rightImageView.image = img
    txtField.rightView = rightImageView
    txtField.rightViewMode = .always



}

这是我为 firstName 文本字段创建的事件处理程序..

@objc func editing()
{
    if(firstName.isEditing == true)
    {
        if(((firstName.text!).count) > 4)
        {
            validColorChange(subject: firstName)

            addRightImage(txtField: firstName, andImage: #imageLiteral(resourceName: "tick"))


        }
        else if(firstName.text == "")
        {

            errorColorChange(subject: firstName)
           <--- //I want to remove image here --->

            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
            sleep(1)

        }
        else
        {
            self.crossLabel.removeFromSuperview()
            self.label.removeFromSuperview()
          <--- //I want to remove image here. --->

        }
    }

非常感谢您的宝贵时间和帮助! 谢谢!

首先将委托分配给您的 textField

然后将此委托方法放入您的代码中

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {


    if textField == txtEmail {


        if textField.text != "" {


            if (textField.text?.count)! < 4 {


                txtEmail.rightViewMode = .never


            }else {


                let rightImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height))
                rightImageView.image = #imageLiteral(resourceName: "ic_notification")
                txtEmail.rightView = rightImageView
                txtEmail.rightViewMode = .always

            }
        }

    }

    return true

}

或者如果你想在你的代码中更改然后输入

firstName.rightViewMode = .never

而不是 .removeFromSuperView