2017-01-03 73 views
0

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

} 
+0

当您前后改变焦点时,您不断向给定的文本字段添加越来越多的图层。 – rmaddy

+0

@rmaddy这是真的。但是,我不相信这种方法可以起作用。 – Kendel

+0

@rmaddy我已经更新了我试图避免重复添加更多图层的问题。同样的结果。 – Kendel

回答

0

为了设置初始边框颜色,我使用了viewDidLayoutSubviews(),这是导致问题的原因。它正在覆盖我在编辑过程中改变的图层。

0

你应该改变文字颜色

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

然后恢复颜色回endEditing委托方法。

+0

这没有帮助。这只是让它在开始输入字符时改变背景。无论如何,同样的问题仍然存在。出于某种原因,在文本视图之间切换时会发生一些不允许我更改图层的奇怪现象。 – Kendel

+0

你使用任何一种键盘库?处理项目中的键盘? –

+0

我认为你应该尝试调度,如果功能正在调用,但用户界面不会在当前时间更新。 –

相关问题