UIAlertController没有出现

时间:2016-05-13 19:37:08

标签: ios swift uialertcontroller

我有一个警报控制器,应该在用户在文本字段中输入不正确数量的字符后出现。警报控制器根本不显示。 w ^

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)
    }
}

2 个答案:

答案 0 :(得分:1)

当你将alertcontroller移动到viewDidAppear-method时,

代码工作正常:

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)
    }

答案 1 :(得分:-2)

以上代码正常运行。 并且alertController.viewDidAppear(false)是不需要的