func designTextField()
{
//Set the horizontal line in bottom of text field
nameLayer.frame = CGRect(x: 0, y: self.tfName.bounds.size.height-1, width: self.tfName.bounds.size.width, height: 1)
nameLayer.backgroundColor = UIColor.lightGray.cgColor
tfName.layer.addSublayer(nameLayer)
//Set the horizontal line in bottom of text field
phoneLayer.frame = CGRect(x: 0, y: self.tfPhone.bounds.size.height-1, width: self.tfPhone.bounds.size.width, height: 1)
phoneLayer.backgroundColor = UIColor.lightGray.cgColor
tfPhone.layer.addSublayer(phoneLayer)
//Set the horizontal line in bottom of text field
emailLayer.frame = CGRect(x: 0, y: self.tfEmail.bounds.size.height-1, width: self.tfEmail.bounds.size.width, height: 1)
emailLayer.backgroundColor = UIColor.lightGray.cgColor
tfEmail.layer.addSublayer(emailLayer)
}
When to use this function to show in the View :
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Text Field Design
self.designTextField()
self.view.layoutIfNeeded()
}
Bottom layer background color will change to blue, when to hit the "Name" text field. But when i type some characters in the text field, then the text field bottom color will change to lightgray(but when i typing then the bottom layer will be same to blue.)
func textFieldDidBeginEditing(_ textField: UITextField)
{
if textField == self.tfName
{
nameLayer.backgroundColor = UIColor(red: 11/255, green: 174/255, blue: 250/255, alpha: 1).cgColor
imgName = UIImage(named: "user2")!
imgVwName.image = imgName
tfName.leftView = imgVwName
}
else if textField == self.tfPhone
{
phoneLayer.backgroundColor = UIColor(red: 11/255, green: 174/255, blue: 250/255, alpha: 1).cgColor
imgPhone = UIImage(named: "phone2")!
imgVwPhone.image = imgPhone
tfPhone.leftView = imgVwPhone
}
else if textField == self.tfEmail
{
emailLayer.backgroundColor = UIColor(red: 11/255, green: 174/255, blue: 250/255, alpha: 1).cgColor
imgEmail = UIImage(named: "mail2")!
imgVwEmail.image = imgEmail
tfEmail.leftView = imgVwEmail
}
}
func textFieldDidEndEditing(_ textField: UITextField)
{
if textField == self.tfName
{
nameLayer.backgroundColor = UIColor.lightGray.cgColor
imgName = UIImage(named: "user1")!
imgVwName.image = imgName
tfName.leftView = imgVwName
}
else if textField == self.tfPhone
{
phoneLayer.backgroundColor = UIColor.lightGray.cgColor
imgPhone = UIImage(named: "phone1")!
imgVwPhone.image = imgPhone
tfPhone.leftView = imgVwPhone
}
else if textField == self.tfEmail
{
emailLayer.backgroundColor = UIColor.lightGray.cgColor
imgEmail = UIImage(named: "mail1")!
imgVwEmail.image = imgEmail
tfEmail.leftView = imgVwEmail
}
}
Can somebody plzz help ???
When you write in textfield viewDidLayoutSubviews
is called every time and call designTextField (designTextField add a new sublayer with grayColor). You can check if is the first time with a flag, or call designTextField in viewWillAppear or viewDidAppear, or check if the layer was added.