2017-08-16 215 views
1

我已經設置了4個TextField並通過textFieldDidChange連接了它們。現在讓我們說我輸入了錯誤的驗證信息,我希望能夠再次選擇TextField並清除所有最後的輸入。我在Swift 3中嘗試didBeginEditing,但它不起作用,因爲它只清除一個TextField而不是全部四個TextField。請幫忙。如何在開始編輯時清除所有TextField或在Swift 3中選擇TextField?

import UIKit 

class verificationVC: UIViewController,UITextFieldDelegate, UITextViewDelegate { 

    @IBOutlet weak var codefirstText: UITextField! 
    @IBOutlet weak var codesecondText: UITextField! 
    @IBOutlet weak var codethirdText: UITextField! 
    @IBOutlet weak var codefourthText: UITextField! 

    func textFieldDidBeginEditing(textField: UITextField) 
    { 
     codefirstText.text = "" 
     codesecondText.text = "" 
     codethirdText.text = "" 
     codefourthText.text = "" 

     if (codefirstText.text != nil) 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codesecondText.text != nil) 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codethirdText.text != nil) 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codefourthText.text != nil) 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
    } 

    func textFieldDidChange (textfield: UITextField) 
    { 
     let text = textfield.text 

     if text?.utf16.count == 1 
     { 
      switch textfield { 
      case codefirstText: 
       codesecondText.becomeFirstResponder() 
      case codesecondText: 
       codethirdText.becomeFirstResponder() 
      case codethirdText: 
       codefourthText.becomeFirstResponder() 
      case codefourthText: 
       codefourthText.resignFirstResponder() 
      default: 
       break 
     } 
    } 
+0

你設置'textfield'委託方法來'self' –

回答

0

由於在Swift中輸入的字符串,字符串不能爲nil。你有沒有試圖控制文本字段的值與空字符串代替nil值:

func textFieldDidBeginEditing(textField: UITextField) 
    { 
     codefirstText.text = "" 
     codesecondText.text = "" 
     codethirdText.text = "" 
     codefourthText.text = "" 

     if (codefirstText.text != "") 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codesecondText.text != "") 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codethirdText.text != "") 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 
     else if (codefourthText.text != "") 
     { 
      codefirstText.text = "" 
      codesecondText.text = "" 
      codethirdText.text = "" 
      codefourthText.text = "" 
     } 

    }