2015-04-04 35 views
1

我需要一種方法來禁用保存按鈕,直到文本輸入到所有必需的文本框中?我正在Swift中開發應用程序,並且在Objective-c中找到了很多答案。因爲我現在已經完全掌握了Objective-C知識,所以我無法弄清楚它的含義。如何禁用一個按鈕,直到所有UITextField中的文本都被輸入爲swift?

有沒有人有這個可以在Swift中完成的解決方案?

我知道如何啓用/禁用按鈕。我也知道如何檢查文本字段是否爲空。我只是不知道如何使它,以便我的代碼總是檢查,看看它是否是空的。我嘗試了一段時間循環,但正如我所料,這一切都凍結了。

+0

我清楚地知道如何啓用/禁用按鈕('button.enabled = FALSE')。我也知道如何檢查一個文本字段是否爲空('if textFieldName ==「」{action}') - 不能做新行,但它會在新行。我的問題是我不知道如何製作,所以它一直在檢查。我不能使用循環,因爲這會凍結我的程序... – cross 2015-04-04 15:42:43

+1

@cross在最後一個評論中,應該說'if textFieldName.text =='「'我也會推薦你設置一個委託。 – cromanelli 2015-04-04 15:46:45

+0

@cromanelli你的權利,謝謝! – cross 2015-04-04 15:49:55

回答

1

使用文本字段的委託方法(或目標操作模式)檢查用戶進行所需的條件。如果他們符合,啓用按鈕。

2

迄今爲止給出的所有評論儘管並沒有炸燬留言區域進一步,我試着就如何解決你的問題的一些提示:

  • 把所有的文本框的出口集合
  • 設置所有文本框的委託給你的viewController
  • 實現委託的didEndEditing方法,並通過出口集合方法迭代內檢查每個文本字段其輸入

請注意,這只是一種實現方法,但您可能會明白。

3

清單來實現這一目標的方法之一:

class ViewController: UIViewController, UITextFieldDelegate { 

    @IBOutlet weak var textField: UITextField! 
    @IBOutlet weak var button: UIButton! 

    //Need to have the ViewController extend UITextFieldDelegate for using this feature 
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 

     // Find out what the text field will be after adding the current edit 
     let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) 

     if !text.isEmpty{//Checking if the input field is not empty 
      button.userInteractionEnabled = true //Enabling the button 
     } else { 
      button.userInteractionEnabled = false //Disabling the button 
     } 

     // Return true so the text field will be changed 
     return true 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     //Setting the Delegate for the TextField 
     textField.delegate = self 
     //Default checking and disabling of the Button 
     if textField.text.isEmpty{ 
      button.userInteractionEnabled = false // Disabling the button 
     } 
    } 
} 

Reference Link for the above solution

相關問題