我有4个文本字段,一个按钮和一个图像,我想要实现的是当按下按钮时它应警告用户有空文本字段并显示指向空文本字段的图像,但是当用户将文本放入空文本字段时,使图像消失。谢谢
这是我的功能
func checkFields(){
let userEmail = user_EmailTxtField.text!
let userPassword = user_PassTxtField.text!
let passwordConfirm = pass_ConfirmTxtField.text!
let userPhone = user_PhoneTxtField.text!
//Set backArrow image to show input error to password
let imageName = "backArrow.png"
let image = UIImage(named: imageName)
let passImageView1 = UIImageView(image: image!)
passImageView1.frame = CGRect(x: 319, y: 331, width: 49, height: 49)
view.addSubview(passImageView1)
//Show Arrow image to password confirm error
let passConfirmImageView1 = UIImageView(image: image!)
passConfirmImageView1.frame = CGRect(x: 319, y: 394, width: 49, height: 49)
view.addSubview(passConfirmImageView1)
//Show arrow Image to email error
let emailImageView1 = UIImageView(image: image!)
emailImageView1.frame = CGRect(x: 319, y: 270, width: 49, height: 49)
view.addSubview(emailImageView1)
//Set image to phonetxt field error
let phoneImageView1 = UIImageView(image: image!)
phoneImageView1.frame = CGRect(x: 319, y: 209, width: 49, height: 49)
view.addSubview(phoneImageView1)
if userPhone.isEmpty {
phoneImageView1.isHidden = false
} else {
phoneImageView1.isHidden = true
}
if userEmail.isEmpty {
emailImageView1.isHidden = false
}
if userPassword.isEmpty {
passImageView1.isHidden = false
}
if passwordConfirm.isEmpty {
passConfirmImageView1.isHidden = false
}
}
答案 0 :(得分:0)
你应该分开图像的创建(addSubview)和检查
将创作设为viewDidLoad
然后检查字段并将其隐藏或显示。
刚才你每次创建一个新图像放在以前创建的图像上(如果你切换到线框3d调试视图,你可以检查这个)
答案 1 :(得分:0)
您应该尝试:
,而不是检查if userPhone.isEmpty
if user_EmailTxtField.text == nil {
phoneImageView1.isHidden = false
}
你甚至可以这样做:
if user_EmailTxtField.text == nil || user_EmailTxtField.text == "" {
phoneImageView1.isHidden = false
}
答案 2 :(得分:0)
您可以调用处理支票的功能,然后如果文字不为空,则隐藏您的图像:
1 在您为text .editingChanged
创建活动的地方的textFields添加目标:
user_EmailTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
user_PhoneTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
pass_ConfirmTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
pass_ConfirmTxtField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
2 设置用于检查文本字段是否被编辑的方法:
func textFieldDidChange() {
emailImageView1.isHidden = user_EmailTxtField.hasText
phoneImageView1.isHidden = user_PhoneTxtField.hasText
passImageView1.isHidden = pass_ConfirmTxtField.hasText
passConfirmImageView1.isHidden = pass_ConfirmTxtField.hasText
}
因此,如果您将此示例应用于所有文本字段,则不需要checkFields()
中的检查,并且您可以将方法重命名为setupTextFields()
,例如仅将其用作创建文本字段
在类中的所有方法中使用图像视图的示例,但请务必在viewDidLoad()
中初始化,以避免在解包可选值时发现nil错误
class YourClass: UIViewController {
// ImageView Reference
var emailImageView1: UIImageView!
// then your checkFields method
func checkFields() {
// code before
emailImageView1 = UIImageView(image: image!)
// code after
}
}