当用户交互结束时,删除自定义UITextField中的嵌套子视图吗?

问题描述 投票:0回答:1

这是我在StackOverflow上的第一篇文章!似乎是一个了不起的社区。

我已经创建了一个自定义UITextfield,它以编程方式具有底线(bottomLine)和阴影线(shadowLine),希望在用户离开文本字段时将其删除。我怎么做?

        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
}()

然后,我实现了UITextFieldDelegate协议及其可选功能之一,以便删除shadowLine子视图,但是它并没有如我所愿地被删除:

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

您能帮个菜鸟吗? :)

swift uitextfield subview programmatically
1个回答
0
投票

似乎您忘记了设置代表:

textField.delagate = self
© www.soinside.com 2019 - 2024. All rights reserved.