Reputation: 207
how can I change the leftview image color while the user is using the keyboard? I want the image to be red if the userNameTextField doesn't contain 6 letter. Thank you very much
here's my code for the leftview image:
userNameTextField.leftViewMode = UITextFieldViewMode.Always
userNameTextField.leftView = UIImageView(image: UIImage(named: "Clipboard-20-2"))
Upvotes: 0
Views: 694
Reputation: 236315
Just add a target to your UITextField for control event EditingChanged and check if the sender character count is less than 6. You also need to set your image rendering mode to always template and set your UITextField leftView tintColor property to red:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let templateImage = UIImage(named: "Clipboard-20-2")?.imageWithRenderingMode(.AlwaysTemplate) { // it will only use your image silhouette tinted with blue or red color
let imageView = UIImageView(image: templateImage)
imageView.tintColor = UIColor.redColor()
userNameTextField.leftViewMode = .Always
userNameTextField.leftView = imageView
}
userNameTextField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
func textChanged(sender: UITextField) {
sender.leftView?.tintColor = sender.text?.characters.count < 6 ? UIColor.redColor() : nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 2