如何在textField中输入一些字符后更改图像

时间:2017-10-27 05:22:13

标签: swift3

我有以下内容:

myImg1 textfield1
  MyImg2 textfield2

以下代码的问题:

用户点击文本字段后,立即更改。

txtfield1.addTarget(self, action: #selector(textFieldShouldBeginEditing(_:)), for: .editingChanged)


func textFieldEditDidBegin(_ textField: UITextField) {

 let newImg: UImage? = UIImage(named: :icon1")
   myImg1.image = newImg
}

textField1和2是否共享上面的代码或不同的代码用于编辑事件?

我需要执行以下操作:

当用户点按或触摸textfeld1并 输入一些字符后,myImg1图片将更改为其他图片

**更新:

How to handle textField2?  How to use this same func for these twp textfields?

txtfield1.addTarget(self, action: #selector(textFieldShouldBeginEditing(_:)), for: .editingChanged)


func textFieldEditDidBegin(_ textField: UITextField) {

 let newImg2: UImage? = UIImage(named: :icon2")
   myImg2.image = newImg2
}

感谢。请帮忙

1 个答案:

答案 0 :(得分:0)

如评论中所述,您可以使用UITextFieldDelegate来识别当前的textField。另请参阅Apple文档:https://developer.apple.com/documentation/uikit/uitextfielddelegate

在您的情况下,如果用户输入专用textField,则应查看以下函数以识别: 不要忘记将delegates设置为txtFields

  class ViewController: UIViewController, UITextFieldDelegate {
       // Your textField
       @IBOutlet weak var txtFieldVar1: UITextField!
       @IBOutlet weak var txtFieldVar2: UITextField!

       override func viewDidLoad() {
          // Don't forget to set the delegate of your available textFields
          self.txtFieldVar1.delegate = self
          self.txtFieldVar2.delegate = self
       }

       func textFieldDidEndEditing(_ textField: UITextField){
          // Do some stuff based on the identified textField
       }
   }