我的UIViewController中有5个textFields,我必须在这些所有textFields上显示底部边框线。
我正在使用FloatLabelTextField
类,并尝试通过编程方式在每个textField上设置底部边框,但第一次(在viewDidLoad方法中)边框线只显示一半。我不知道为什么会这样。
这是我的代码:
import UIKit
class ViewController: UITableViewController {
@IBOutlet var vwName: FloatLabelTextField!
override func viewDidLoad() {
super.viewDidLoad()
vwName.delegate = self
setBottomBorder(textField: vwName, width: 0.8, color: .darkGray)
}
}
extension ViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if let sublayers = textField.layer.sublayers {
for layer: CALayer in sublayers {
if layer.name == "BottomBorder" {
layer.removeFromSuperlayer()
}
}
}
setBottomBorder(textField: textField, width: 0.8, color: .blue)
}
func textFieldDidEndEditing(_ textField: UITextField) {
if let sublayers = textField.layer.sublayers {
for layer: CALayer in sublayers {
if layer.name == "BottomBorder" {
layer.removeFromSuperlayer()
}
}
}
setBottomBorder(textField: textField, width: 0.8, color: .lightGray)
textField.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension ViewController {
func setBottomBorder(textField: UITextField, width: CGFloat, color: UIColor) {
let border = CALayer()
border.name = "BottomBorder"
border.borderColor = color.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: width)
border.borderWidth = width
textField.borderStyle = UITextBorderStyle.none
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true
}
}
如果我点击文字字段,那么边框线就会正常显示。我的意思是当TextFieldDidBeginEditing
委托方法调用时边界线显示正确。
但最初在查看加载时它会显示一半。