[英]How to access function variable and remove it from superview?
我創建了一個函數,如果您鍵入四個以上的字符,textField會在拐角處顯示帶有綠色勾號的圖像,但是當我刪除textField內的所有字符時,它會顯示一條錯誤消息,但我想刪除該綠色勾號圖像。 我試過了
.removeFromSuperView
但這不起作用。
我很難從函數中訪問變量以將其從Superview中刪除。
這是我在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. --->
}
}
感謝您的時間和幫助! 謝謝!
首先將委托分配給您的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.