2016-11-24 15 views
0

私はUITextFieldを含むUIAlertViewを持っています。アラートビューにはトウボタンがあります。 1つの通常の「解除」ボタンと別の「追加」ボタン。 UITextFieldが空でない場合は、[追加]ボタンをクリックできるだけです。フィールドが空の場合、「リアルタイム」でチェックインする方法はわかりません。私は、ボタンがクリックされた場合にtextFieldをチェックする可能性を見ただけです。しかし、それは何が欲しいのではないのですか(「追加」ボタンは、テキストフィールドが空の場合はグレー表示にする必要があります)。これに対する解決策はありますか?お疲れ様でした!UITextFieldが空でない場合、ライブを確認してください。

私はスウィフト3とXcodeを使用しています8

+0

実施例です。 – sdasdadas

+0

'UIAlertView'はしばらく前に廃止されました。あなたは 'UIAlertController'を使うべきです。 – rmaddy

答えて

3

UIAlertControllerにそのアクションを追加しながらあなたは以下のコード

alertAction = UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil) 
alertAction.isEnabled = false 
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert) 
alert.addTextField { (textField) in 
    textField.delegate = self 
}   
alert.addAction(alertAction) 
self.present(alert, animated: true, completion: nil) 
中などの偽のプロパティ isEnabledを設定する必要が今この

var alertAction = UIAlertAction() 

のようなグローバル変数としてあなたUIAlertActionを作成する必要があります

代理メソッドのshouldChangeCharacterの後に、値がUITextFieldに入力されている場合、このようなボタンを有効にする必要があります。

ここ
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     let userEnteredString = textField.text 
     let newString = (userEnteredString! as NSString).replacingCharacters(in: range, with: string) as NSString 
     if newString != ""{ 
      alertAction.isEnabled = true 
     } else { 
      alertAction.isEnabled = false 
     } 
     return true 
    } 

は、あなたが変更をリッスンするUITextFieldDelegateを使用したいと思う

enter image description here

+0

すばらしい答え!どうもありがとう!それは動作します:) – Vpor

+0

あなたはこれを使用するすべてのviewcontrollerでデリゲートパターンを実装する必要がないようにこれをユーティリティクラスにするために何をすべきか知っていますか?私はそれにいくつかの問題があります(http://stackoverflow.com/questions/40837477/uialertcontroller-utility-class-fails-to-call-uitextfield-delegate-or-target-but/40838396#40838396) – xxtesaxx

0

チェックテキストフィールドのテキスト:あなたはTextFieldDelegateをすることができます

if textField.text != nil && textField.text != "" { 
    print("you can enable your add button") 
}else{ 
    print("empty text field") 
} 
0

。現在のビューコントローラまたはビューをデリゲートとして設定する

let textTextField = UITextField() 
textTextField.delegate = self 

テキストフィールドを変更すると、以下のメソッドが呼び出されます。

func textField(_ textField: UITextField, 
shouldChangeCharactersIn range: NSRange, 
     replacementString string: String) -> Bool 

か、テキストフィールドのテキストが変更されます時に掲載されます.IT UITextFieldTextDidChange通知を使用することができます。

影響を受けるテキストフィールドは、通知のオブジェクトパラメータに格納されます。

関連する問題