我希望错误图标图像将在UITextField中自动显示,其中一个验证在
swift中失败.
验证失败时,这是错误阶段
对于那个UITextField,我创建了自定义UITextField,如下所示
class ovalTextField: UITextField { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! createBorder() } required override init(frame: CGRect) { super.init(frame: frame) createBorder() } func createBorder(){ let errorImg = UIImageView (frame: CGRectMake(0,30,30)) errorImg.image = UIImage(named: "error") errorImg.contentMode = UIViewContentMode.Left self.layer.borderWidth = 1.0 self.layer.borderColor = UIColor(red:0.93,green:0.93,blue:0.93,alpha:1.0).CGColor self.layer.cornerRadius = self.frame.size.height / 2 self.layer.masksToBounds = true let gapLabel = UIView (frame: CGRectMake(60,10,40)) self.leftView = gapLabel self.leftviewmode = UITextFieldviewmode.Always /* display that one when validation is Failed */ self.rightView = errorImg; self.rightviewmode = UITextFieldviewmode.Always } }
并在ViewController中使用了UITextField,
@IBOutlet var txtEmail: ovalTextField!
如果该txtEmail为空或无效的电子邮件地址,我想显示错误图标消息.
请建议我怎么做.提前致谢.
解决方法
您可以使用UITextFiledDelegate方法func textField(textField:UITextField,shouldChangeCharactersInRange range:NSRange,replacementString string:String) – > Bool在用户输入时验证电子邮件.
>首先设置委托,txtEmail.delegate = self,然后
>实现委托方法
func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool { let email = (textField.text! as Nsstring).stringByReplacingCharactersInRange(range,withString: string) if /* email is validate */ { textField.rightView?.hidden = false } else { textField.rightView?.hidden = true } return true
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。