2016-05-13 91 views
1

我有一個警報控制器,應該在用戶在文本字段中輸入不正確數量的字符後出現。警報控制器根本沒有出現。 WUIAlertController not displayed

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

你不應該需要調用'viewDidAppear'法第所有。然後檢查**主線程中提供的alertController ** – ridvankucuk

回答

-2

以上代碼正常工作。 而alertController.viewDidAppear(假)是不需要

1

代碼工作正確的,當u移動alertcontroller IE瀏覽器viewDidAppear法:

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

如果所有警報控制器代碼都在'if'語句內移動,那將會更好。爲什麼創建並設置警報,如果它不會顯示? – rmaddy

+1

爲什麼你認爲這個代碼需要在'viewDidAppear:'?這沒有理由。 – rmaddy

+0

@rmaddy不,你是真的,我不知道爲什麼**。我發現,當我有一個類似的問題。 viewDidLoad似乎要遲到了... –