Search code examples
swiftuitextfieldsubview

Remove a nested subview inside custom UITextField when user interaction did end?


This is my first post on StackOverflow! Seems to be an amazing community.

I have created a custom UITextfield with a bottom line (bottomLine) programmatically and also a shadowed line (shadowLine) that I wish should be removed when the user moves away from the textfield. How do I do that?

        lazy var textField: UITextField = {
    let textField = UITextField()
    textField.anchor(width: 150, height: 22)
    textField.backgroundColor = UIColor(white: 100, alpha: 1)
        var bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0, y: 22, width: 150, height: 1)
        bottomLine.backgroundColor = UIColor.black.cgColor
        textField.borderStyle = UITextField.BorderStyle.none
    textField.layer.addSublayer(bottomLine)
    let shadowLine = UIView()
    shadowLine.frame = CGRect(x: 0, y: 22, width: 150, height: 3)
        shadowLine.backgroundColor = UIColor.black
    shadowLine.layer.shadowColor = UIColor.darkGray.cgColor
    shadowLine.layer.shadowOffset = CGSize(width: 3, height: 3)
    shadowLine.layer.shadowRadius = 3
    shadowLine.layer.shadowOpacity = 1
    shadowLine.tag = 1
    textField.addSubview(shadowLine)
    return textField
}()

Then I implemented the UITextFieldDelegate protocol and one of its optional functions in order to remove shadowLine subview but it doesn't get removed as I want to:

    func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == textField {
        textField.viewWithTag(1)?.removeFromSuperview()
    }
}

Can you help a rookie out? :)


Solution

  • It looks like you forgot to set the delegate:

    textField.delagate = self