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)
}
何时使用此功能在视图中显示:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Text Field Design
self.designTextField()
self.view.layoutIfNeeded()
}
输出:
当点击“名称”文本字段时,底层背景颜色将变为蓝色。但是,当我在文本字段中键入一些字符时,文本字段的底部颜色将变为浅灰色(但当我键入时,底部图层将与蓝色相同)
输出:
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
}
}
有人能帮忙吗???
最佳答案
每次调用designTextField并调用designTextField(designTextField添加带有灰色的新子层)时,都会调用textfieldviewDidLayoutSubviews
。您可以检查是否是第一次使用标志,或调用viewWillAppear或viewDidAppear中的designTextField,或检查是否添加了层。