Swift从不同的控制器调用视图控制器或从不同的控制器调用警报

时间:2018-04-18 04:14:43

标签: ios swift alert

我想知道是否有可能在swift中调用警报或控制器或从单独的控制器中调用一个函数。我想从viewcontroller1到app delegate访问我的警报,我想在app delegate中触发它而不是创建另一个警报,我有一个目的,为什么我想在app delegate中触发它。这可能吗?谢谢 。我可以在app delegate中的视图控制器1中调用我的警报吗?而且我想从app delegate中的视图控制器1调用我的集合视图是可能的吗?

集合视图代码

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
//        print("You selected cell #\(indexPath.item)!")
//        print("emong gepili:" , titleArray[indexPath.row])


        if indexPath.row == 0 {
            var a = loggedInUsername
            if ((a?.range(of: "mother")) != nil) {
                  performSegue(withIdentifier: "goToSegue", sender: nil)
                print("yolo")
            }else {
                print("do nothing")
                var alert = UIAlertController(title: "No Access", message: "You Can't Add A Chore", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }

        } else {


            print("You selected cell #\(indexPath.item)!")

            if let getTempDetails: [String : Any] = getAllDetail[indexPath.row],
                let name = getTempDetails["name"] as? String,
                let id = getTempDetails["id"] as? Int,
                let description = getTempDetails["desc"] as? String,
                let chorereward = getTempDetails["reward"] as? String,
                let choreschedule = getTempDetails["sched"] as? String

                //                let chorescheds = getTempDetails["sched"] as? String

//                let parent = getTempDetails["parent"] as? String,
//                let child = getTempDetails["child"] as? String,
//                let occurrence = getTempDetails["occurrence"] as? String,
//                let status = getTempDetails["date_created"] as? String,
//                let datec = getTempDetails["status"] as? String,
//                let datemod = getTempDetails["date_modified"] as? String {
            {
                let stat = getTempDetails["status"] as! NSDictionary
                let statname = stat["name"]
                let str = getTempDetails["occurrence"] as! NSDictionary
                let strname = str["name"]

警报代码

let alert = UIAlertController(title: "Chore Name: \(getTempDetails["name"] as! String)", message: "", preferredStyle:
                    UIAlertControllerStyle.alert)


                alert.addTextField { (choreField) in
                    choreField.text = getTempDetails["name"] as! String
                }



                alert.addTextField { (rewardField) in
                    //                    rewardField.text =  getTempDetails["reward"] as! String
                    let rewardData = getTempDetails["reward"]
                    let reward = (rewardData as! NSString).integerValue
                    rewardField.placeholder = "Chore Reward"
                    rewardField.text = String(reward)
                }

                alert.addTextField { (idField) in
                    idField.placeholder = "Email"
                    var a =  "\(getTempDetails["id"] as? Int ?? 0)!"
                    a.removeLast()
                    idField.text = a
                }
                ........

3 个答案:

答案 0 :(得分:1)

使用此扩展程序在应用程序的任何位置显示Alert或ViewController:

extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let navigationController = controller as? UINavigationController {
        return topViewController(controller: navigationController.visibleViewController)
    }
    if let tabController = controller as? UITabBarController {
        if let selected = tabController.selectedViewController {
            return topViewController(controller: selected)
        }
    }
    if let presented = controller?.presentedViewController {
        return topViewController(controller: presented)
    }
    return controller
}

}

如何使用?

UIApplication.topViewController()?.present(yourAlertVC, animated: true, completion: nil)
  

现在我从你的问题中理解了什么,

     

显然,从AppDelegate调用集合视图的委托方法是一种错误的方法,因为iOS Geek说它是Singleton。   但你可以做的就是为那个人创造一个观察者   下面的一个。

NotificationCenter.default.addObserver(self, selector: #selector(theMethodWhichYouWanaHit(params:)), name: Notification.Name("Notification_Name"), object: nil)

以下是方法:

func theMethodWhichYouWanaHit(_ params : Notification){
    collectionView.delegate = self
    collectionView.dataSource = self
    let yourObject = params.object
    // use the object it has all the data in it (aka objectToBePassed )
}

你已经完成了。!

现在,就像一个函数调用一样发布观察者,它将完成其余的工作:

NotificationCenter.default.post(name: NSNotification.Name("Notification_Name"), object: objectToPassed, userInfo:nil)

为了删除观察者:

NotificationCenter.default.removeObserver(self, name: NSNotification.Name("Notification_Name"), object: nil)

答案 1 :(得分:0)

创建一个新的NSObject类,并将全局函数作为其类func,如下面的示例所示

  class wrapperClass: NSObject
    {
       class func alert(_ title : String, message : String, view:UIViewController)
        {
            let alert = UIAlertController(title:title, message:  message, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            view.present(alert, animated: true, completion: nil)
        }
    }

<强>用法

wrapperClass.alert("Service Remainder", message: "Enter Username", view: self)

注意 - AppDelgate不是View控制器,因此您无法在AppDelegate中调用此函数您可以在第一个控制器中执行一项操作显示

答案 2 :(得分:0)

根据我的underStanding,您正试图在AppDelegate期间显示提醒。

但是不可能在那里展示,基本上会发生什么是在应用程序启动时调用AppDelegate,之后将调用堆栈中第一个的View控制器。

如果您在AppDelegate中创建了任何条件,并且在那种情况下想要在那里显示警告,

您可以使用

func showAlertAppDelegate(title : String,message : String,buttonTitle : String,window: UIWindow){ 
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil)) 
window.rootViewController?.present(alert, animated: true, completion: nil) 
}

并使用它:

showAlertAppDelegate(title: "Alert!", message: "Message", buttonTitle: "Ok", window: self.window!)

注意: - 此警报将显示在调用App委托后将加载的第一个VC上。