Search code examples
iosobjective-cpresentviewcontroller

present view controller in UIContentView


I'm having pageViewController(ABC) at rootViewController and pageViewController contains ViewController(PQR) Which contains ContentView. I want to Present ViewController but it is saying

Warning: Attempt to present XYZ: 0x17ee0730 on ABC: 0x17e67dc0 whose view is not in the window hierarchy!

On which controller I suppose to present View controller


Solution

  • Glad that your problem is solved. Incase if you want to display alert, from any UIView other than a view controller, this would help.

    This method gets the top view controller, so that you can present your alert from it:

    func currentTopViewController() -> UIViewController{
    
        var topVC: UIViewController? = UIApplication.shared.delegate?.window??.rootViewController
    
        while ((topVC?.presentedViewController) != nil) {
    
            topVC = topVC?.presentedViewController
    
        }
    
        return topVC!
    
    }
    
    func showAlert() { // This presents your alert from the received view controller object
    
        let alertController: UIAlertController = UIAlertController.init(title: "title", message: "message", preferredStyle: .alert)
    
        let alertAction = UIAlertAction.init(title: "OK", style: .default) { (UIAlertAction) in
                //Your action    
        }
    
        alertController.addAction(alertAction)
    
        currentTopViewController().present(alertController, animated: true, completion: nil)
    
    }