Кнопка Alert, чтобы закрыть Alert и go вернуться к предыдущему View Controller - PullRequest
0 голосов
/ 28 мая 2020

Я новичок в Swift и не могу понять этого. У меня есть оповещение, которое должно отображаться при успешном запросе URL. После того, как пользователь нажимает кнопку Ok в предупреждении, мне нужно, чтобы предупреждение было отклонено, и мне нужно, чтобы представленный контроллер go вернулся в стек навигации к предыдущему контроллеру представления. Я не получаю ошибок, но ничего не происходит. Если я перенесу весь код для оповещения внутрь CustomClass, он будет работать нормально. Я предполагаю, что неправильно ссылаюсь на CustomClass. Любая помощь будет принята с благодарностью!

 struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}

Ответы [ 4 ]

2 голосов
/ 28 мая 2020

Похоже, каждый раз, когда вы вызываете свою функцию, вы создаете новый контроллер представления. Поэтому ничего не происходит. Попробуйте использовать закрытие, реализовать функцию оповещения как расширение для UIViewController или передать ее как вход функции. Выберите то, что больше всего соответствует вашим потребностям.

1 голос
/ 28 мая 2020

Измените предупреждение так, чтобы оно находилось внутри расширения UIViewController и используйте self, чтобы отклонить, и popViewController в стеке навигации, вот код:

extension UIViewController {
    func CustomAlert(title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            self.navigationController?.popViewController(animated: true)
        }))
         present(myAlert, animated: true, completion: nil)
    }
 }

Использование:

class: CustomClass: UIViewController {

    function Download(){

      // code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200") {
            self.CustomAlert(title: "", message: "")
        }
      }
    }
}
1 голос
/ 28 мая 2020

Не создавайте новый экземпляр let vc = CustomClass() используйте тот, который вы передали в качестве параметра

struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? CustomClass {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}

И лучше использовать протокол вместо класса жесткого кода

protocol Goback {
    func GoBackToPreviousVC()
}


struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? Goback {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}

И подтвердите свой класс с помощью тот протокол, в котором вы хотите использовать Alert

class CustomClass: UIViewController,Goback {

    func GoBackToPreviousVC(){

        navigationController?.popViewController(animated: true)
    }
}
0 голосов
/ 28 мая 2020

Swift 5.3

Вы добавляете служебный класс. Я использую вот так.

public class UtilsClass: NSObject  {
    public static let shared = UtilsClass()

    public func customAlertYN(ViewController:UIViewController,title:String!,actionTitle:String!,message:String!,okButtonString:String!,cancelButtonString:String!,okCallback: @escaping () -> Void = {}){
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let ok = UIAlertAction(title: okButtonString, style: .default, handler: { (action) -> Void in
                okCallback()
            })

            let cancel = UIAlertAction(title: cancelButtonString, style: .cancel) { (action) -> Void in

            }

            alert.addAction(ok)
            alert.addAction(cancel)
            ViewController.present(alert, animated: true, completion: nil)
        }
      }

И так использую. Добавьте свой viewController.

UtilsClass.shared.customAlertYN(ViewController: self, title: "Alert", actionTitle: "", message: "Are you sure you want to logout?", okButtonString: "Yes", cancelButtonString: "No",okCallback: {
                //TODO: 
   })
...