Проверка по нажатию кнопки и изменение вида контроллера iOS - PullRequest
0 голосов
/ 10 сентября 2018

Я новичок в разработке Swift для iOS, и я создаю страницу входа пользователя, и когда они нажимают кнопку Sign In, при вводе пользователя выполняется некоторая проверка, и в случае успеха отправляют пользователя новому стр. В раскадровке у меня есть два контроллера представления: страница входа и страница после успешного входа. Я создал переход от кнопки Sign In на странице входа ко второй странице. Вот следующий код.

@IBAction func loginAction(_ sender: Any) {
    guard let username = usernameField.text, let password = passwordField.text else {
        return
    }
    if (username.isEmpty && password.isEmpty) {
        displayAlert(message: "username and password are not set")
        return
    }
    if (username.isEmpty) {
        displayAlert(message: "username is not set")
        return
    }
    if (password.isEmpty) {
        displayAlert(message: "password is not set")
        return
    }
}

Этот код работает и успешно отправляет пользователя на правильную страницу после входа в систему. Но когда я добавляю предупреждение, которое говорит "Success", новая страница не загружается после закрытия предупреждения. Вот код, который добавляет предупреждение для успешного входа в систему. Код добавляется сразу после окончательного условия в функцию loginAction.

let alert = UIAlertController(title: "Success", message: "Sucessfully logged in", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

По какой причине меня не отправляют на новую страницу с этим предупреждением? Если предупреждение "Success" закомментировано, я отправляюсь на правильную страницу.

Я использую Xcode 9 и Swift 4.

Редактировать: Вот класс кода.

class ViewController: UIViewController {
    @IBOutlet weak var usernameField: UITextField!
    @IBOutlet weak var passwordField: UITextField!

    @IBAction func loginAction(_ sender: Any) {
        guard let username = usernameField.text, let password = passwordField.text else {
            return
        }
        if (username.isEmpty && password.isEmpty) {
            displayAlert(message: "username and password are not set")
            return
        }
        if (username.isEmpty) {
            displayAlert(message: "username is not set")
            return
        }
        if (password.isEmpty) {
            displayAlert(message: "password is not set")
            return
        }
        login(info: username)
        // self.present(alert, animated: true, completion: nil)
        // self.present(self, animated: true) {
        //     let alert = UIAlertController(title: "Success", message: "Sucessfully logged in with \(username)", preferredStyle: UIAlertControllerStyle.alert)
        //     alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil))
        //     self.present(alert, animated: true, completion: nil)
        // }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func login(info: String) {
        let alert = UIAlertController(title: "Success", message: "Sucessfully logged in with \(info)", preferredStyle: UIAlertControllerStyle.alert)
        // alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default) { action in self.dismiss(animated: true) })
        alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    private func displayAlert(message: String) {
        let alert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

1 Ответ

0 голосов
/ 10 сентября 2018

Это то, что мне нужно было сделать, чтобы заставить его работать должным образом. Я обновил свою функцию loginAction.

let alert = UIAlertController(title: "Success", message: "Sucessfully logged in with \(info)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default) { action in
    self.performSegue(withIdentifier: "loginSegue", sender: nil)
})
self.present(alert, animated: true, completion: nil)
...