2016-05-13 26 views
1

Ich habe einen Alarm-Controller, der angezeigt werden soll, nachdem ein Benutzer eine falsche Anzahl von Zeichen in die Textfelder eingegeben hat. Der Alarm-Controller wird überhaupt nicht angezeigt. WUIAlertController wird nicht angezeigt

func usernameFieldCharacters() { 
    let alertController = UIAlertController(title: "Alert", message: "Five characters or more is required in all fields" , preferredStyle: UIAlertControllerStyle.Alert) 

    let okAction = UIAlertAction(title: "OK", style: .Default) { 

    action -> Void in // Does not do anything 
    } 

    alertController.addAction(okAction) // adds the OK button to 
    // to alert controller 

    let allowedChars = 5 // character amount has to be equal or greater in each field 
    let usernameCount = theUsernameField.text?.characters.count 

    if usernameCount < allowedChars { 
     self.presentViewController(alertController, animated: true, completion: nil) 
    } else { 
     alertController.viewDidAppear(false) 
    } 
} 
+0

Sie sollten nicht den Anruf benötigen 'viewDidAppear' Methode zuerst alle. Überprüfen Sie dann alertController, das im ** Hauptthread angezeigt wird. ** – ridvankucuk

Antwort

-2

Der obige Code funktioniert korrekt. Und alertController.viewDidAppear (false) ist der Code funktioniert richtig, nicht

1

brauchen, wenn u die alertcontroller bewegen viewDidAppear-Methode, dh:

class ViewController: UIViewController { 

    override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 

    let allowedChars = 5 // character amount has to be equal or greater in each field 

    let usernameCount = theUsernameField.text?.characters.count 

    if usernameCount < allowedChars { 
     // Do any additional setup after loading the view, typically from a nib. 
     let alertController = UIAlertController(title: "Alert", message: "Five characters or more is required in all fields" , preferredStyle: UIAlertControllerStyle.Alert) 

     let okAction = UIAlertAction(title: "OK", style: .Default) { 

      action -> Void in // Does not do anything 
     } 

     alertController.addAction(okAction) // adds the OK button to 
     // to alert controller 

     self.present(alertController, animated: true, completion: nil) 
    } 
+0

Es wäre noch besser, wenn der gesamte Code des Alarm-Controllers in die 'if'-Anweisung verschoben würde. Warum sollte der Alarm erstellt und eingerichtet werden, wenn er nicht angezeigt wird? – rmaddy

+1

Und warum sollten diese Codes in 'viewDidAppear:' stehen? Dafür gibt es keinen Grund. – rmaddy

+0

@rmaddy nein, du bist richtig, ich wusste nicht ** warum **. Ich fand das, als ich ein ähnliches Problem hatte. Der viewDidLoad scheint zu spät zu sein ... –