我创建了一个函数,如果您键入四个以上的字符,textField会在拐角处显示带有绿色勾号的图像,但是当我删除textField中的所有字符时,它将显示错误消息,但我想删除该绿色勾号图像。我尝试过
.removeFromSuperView
但它不起作用。
我很难访问函数中的变量以将其从超级视图中删除。
这是我在textField中创建图像的代码(最右侧)
func addRightImage(txtField: UITextField, andImage img:UIImage)
{
let rightImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height))
rightImageView.image = img
txtField.rightView = rightImageView
txtField.rightViewMode = .always
}
这是我为firstName文本字段创建的事件处理程序。
@objc func editing()
{
if(firstName.isEditing == true)
{
if(((firstName.text!).count) > 4)
{
validColorChange(subject: firstName)
addRightImage(txtField: firstName, andImage: #imageLiteral(resourceName: "tick"))
}
else if(firstName.text == "")
{
errorColorChange(subject: firstName)
<--- //I want to remove image here --->
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
sleep(1)
}
else
{
self.crossLabel.removeFromSuperview()
self.label.removeFromSuperview()
<--- //I want to remove image here. --->
}
}
您的时间和帮助将不胜感激! 谢谢!
答案 0 :(得分:0)
首先将委托分配给您的textField
然后将此委托方法放入您的代码中
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == txtEmail {
if textField.text != "" {
if (textField.text?.count)! < 4 {
txtEmail.rightViewMode = .never
}else {
let rightImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height))
rightImageView.image = #imageLiteral(resourceName: "ic_notification")
txtEmail.rightView = rightImageView
txtEmail.rightViewMode = .always
}
}
}
return true
}
或者如果您想更改代码,则输入
firstName.rightViewMode = .never
代替.removeFromSuperView