Noob in Swift
Noob in Swift

Reputation: 113

How to access function variable and remove it from superview?

I have created a function where if you type more than four characters , textField displays an image at the corner with a green tick but when I remove all the characters inside textField , it displays an error message but I want to remove that green tick image. I tried

.removeFromSuperView

but it doesn't work.

I am having a hard time accessing a variable from a function to remove it from superview.

This is my code for creation of an image in the textField (extreme right)

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



}

and this is an event handler which I created for firstName textfield..

@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. --->

        }
    }

Your time and help will be highly appreciated! Thank you!

Upvotes: 0

Views: 100

Answers (1)

Mahesh Dangar
Mahesh Dangar

Reputation: 804

first of all assign delegate to your textField

and then put this delegate method in your code

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

}

or if you want to chnage in your code then put

firstName.rightViewMode = .never

instead of .removeFromSuperView

Upvotes: 0

Related Questions