繁体   English   中英

编辑时如何更改UITextField

[英]How to Change UITextField When Editing

我的视图控制器中有多个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
    }

}

您应该更改文本颜色

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
       // textfield.backgrounColor = UIColor.yourselectedcolor
        return true
    }

然后在endEditing委托方法中还原颜色。

为了设置初始边框颜色,我使用了viewDidLayoutSubviews() ,这引起了问题。 它覆盖了我在编辑过程中更改的图层。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM