如何在用户使用键盘时更改leftview图像颜色?如果userNameTextField不包含6个字母,我希望图像为红色。 非常感谢你
这是我的左视图图片代码:
userNameTextField.leftViewMode = UITextFieldViewMode.Always
userNameTextField.leftView = UIImageView(image: UIImage(named: "Clipboard-20-2"))
答案 0 :(得分:1)
只需将目标添加到UITextField以获取控件事件EditingChanged并检查发件人字符数是否小于6.您还需要将图像呈现模式设置为始终模板并将UITextField leftView tintColor属性设置为红色:
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.
}
}