当用户交互结束时删除自定义 UITextField 中的嵌套子视图?
Remove a nested subview inside custom UITextField when user interaction did end?
这是我在 Whosebug 上的第一个 post!似乎是一个了不起的社区。
我以编程方式创建了一个带有底线 (bottomLine) 和阴影线 (shadowLine) 的自定义 UITextfield,我希望在用户离开文本字段时将其删除。我怎么做?
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()
}
}
你能帮助菜鸟吗? :)
您似乎忘记设置委托:
textField.delagate = self
这是我在 Whosebug 上的第一个 post!似乎是一个了不起的社区。
我以编程方式创建了一个带有底线 (bottomLine) 和阴影线 (shadowLine) 的自定义 UITextfield,我希望在用户离开文本字段时将其删除。我怎么做?
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()
}
}
你能帮助菜鸟吗? :)
您似乎忘记设置委托:
textField.delagate = self