2016-04-22 7 views
0

アラートボックスから入力を迅速に取得するにはどうすればよいですか?私のコードがなぜ機能していないのか分かりません。私はC++のプログラマーですので、私は非常に迅速です。何らかの理由で私のプリントラインに着くと、「新しいスタイルが追加されました:」と表示されます。それはprint("New Style Added is: " + tempStyle)tempStyle = textField.text!を追加してみてください。ここに私のコードはSwiftのアラートボックスから入力を取得するにはどうすればよいですか?

ある
// Generate a text field for user input 
    func generateTextField() 
    { 

     //1. Create the alert controller. 
     var tempStyle = ""; 
     var alert = UIAlertController(title: "Add a New Style", message: "Enter the name of the new hairstyle below", preferredStyle: .Alert); 


     //2. Add the text field. You can configure it however you need. 
     alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in 
      textField.placeholder = "Your New Hairstyle Goes Here.."; 
     }) 

     //3. Grab the value from the text field, and print it when the user clicks OK. 
     alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in 
      let textField = alert.textFields![0] as UITextField 
      tempStyle = textField.text!; 

     })) 


     // 4. Present the alert. 
     self.presentViewController(alert, animated: true, completion: nil) 


     print("New Style Added is: " + tempStyle); 

    } 

答えて

1

..ユーザーが何らかの理由でテキストボックスに入力された内容を表示しません。 printコマンドが適切な場所で呼び出されていないようです。すべてのtempStyleは、それが ""と等しいことを知っています。変数が変更された関数にコードを追加するか、var tempStyle = ""をクラス全体の変数にする必要があります。この場合、関数の外に変数を追加します。これをクラス全体の変数にする場合は、print("New Style Added is: " + tempStyle)のままにしておきますが、tempStyleがそのクラス(そのviewController)で作成された面を参照して、print("New Style Added is: " + self.tempStyle)にする必要があります。また、 ";"は必要ありません。スウィフトでは、私はそれがObjective Cからの習慣の力だと思います!

関連する問題