我有一个名为textfieldEdit的UItextfield子类,我在其中更改了文本字段的边框颜色。
在我的viewcontroller中,我将textfieldEdit附加到文本字段,如果用户没有在文本字段中输入值,我希望能够更改文本字段的颜色。我怎样才能做到这一点?
textfieldEdit.swift:
class textfieldEdit: UITextField, UITextFieldDelegate {
let border = CALayer()
let width = CGFloat(2.0)
required init?(coder aDecoder: (NSCoder!)) {
super.init(coder: aDecoder)
self.delegate=self;
border.borderColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 100).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
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
@objc(textFieldDidBeginEditing:) func textFieldDidBeginEditing(_ textView: UITextField) {
border.borderColor = UIColor( red: 116/255, green: 193/255, blue: 166/255, alpha: 100 ).cgColor
textColor = UIColor( red: 116/255, green: 193/255, blue: 166/255, alpha: 100 )
}
@objc(textFieldDidEndEditing:) func textFieldDidEndEditing(_ textView: UITextField) {
border.borderColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1).cgColor
}
override func draw(_ rect: CGRect) {
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
}
override func awakeFromNib() {
super.awakeFromNib()
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
}
}
RegisterViewController:
class RegisterVC: UIViewController, UITextFieldDelegate {
// declare UI objects
@IBOutlet weak var usernameTxt: UITextField!
@IBOutlet weak var passwordTxt: textfieldEdit!
@IBOutlet weak var emailTxt: UITextField!
@IBOutlet weak var fullnameTxt: UITextField!
@IBOutlet weak var registerBtn: UIButton!
// first function that is loaded
override func viewDidLoad() {
super.viewDidLoad()
} // end of viewDidLoad function
// function that will be performed when clicking the register button
@IBAction func register_click(_ sender: Any) {
// if registered button is clicked and textfields are empty
if usernameTxt.text!.isEmpty {
// display red placeholders for empty textfields
usernameTxt.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
答案 0 :(得分:0)
我已编辑此代码。我的代码可以帮助您。
public func textFieldDidBeginEditing(_ textField: UITextField) // became first responder
{
if (txtCurrent != nil)
{
txtCurrent.layer.borderColor = UIColor(red: 206/255.0, green: 215/255.0, blue: 221/255.0, alpha: 1.000).cgColor
}
txtCurrent = textField
txtCurrent.layer.borderColor = UIColor(red: 67/255.0, green: 153/255.0, blue: 201/255.0, alpha: 1.000).cgColor
}
public func textFieldDidEndEditing(_ textField: UITextField)
{
txtCurrent.layer.borderColor = UIColor(red: 206/255.0, green: 215/255.0, blue: 221/255.0, alpha: 1.000).cgColor
}