我的视图控制器中有多个UITextField,它也是一个文本字段委托。出于某种原因,以下代码仅在没有任何选中之后选择文本字段时才起作用。如果我在文本字段之间切换,那么我要离开的文本字段会发生变化,但我正在编辑的字段不会变为红色。我调试并发现,即使在两者之间切换时也调用这两种方法,但出于某种原因,它不会为您正在编辑的那个设置颜色。任何帮助是极大的赞赏。谢谢!如何在编辑时更改UITextField
func textFieldDidBeginEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.red)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.lightGray)
}
func setTextBorder(textField: UITextField, color: UIColor) {
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = color.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: textField.frame.size.height)
border.borderWidth = width
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true
}
编辑
我现在创建一个自定义的类来测试,看看问题是,我不断添加子层的事实。我得到了同样的结果。这是自定义文本字段级的我做:
class SpecialTextField: UITextField {
var currentBorder: CALayer?
func setTextBorder(color: UIColor) {
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
if (currentBorder == nil) {
self.layer.addSublayer(border)
self.layer.masksToBounds = true
} else {
self.layer.replaceSublayer(self.currentBorder!, with: border)
}
self.currentBorder = border
}
}
当您前后改变焦点时,您不断向给定的文本字段添加越来越多的图层。 – rmaddy
@rmaddy这是真的。但是,我不相信这种方法可以起作用。 – Kendel
@rmaddy我已经更新了我试图避免重复添加更多图层的问题。同样的结果。 – Kendel