PresentViewController 不起作用:视图不在 TabBarController 的窗口层次结构中



我创建了一个CustomAlertView。

protocol CustomAlertViewControllerDelegate{
func retryToFetchData()
}
class CustomAlertViewController: UIViewController {
@IBOutlet weak var alertView: UIView!
var delegate: CustomAlertViewControllerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.alertView.alpha = 0
self.alertView.frame.origin.y = self.alertView.frame.origin.y + 50
UIView.animate(withDuration: 0.4) {
self.alertView.alpha = 1.0
self.alertView.frame.origin.y = self.alertView.frame.origin.y - 50
}
}

@IBAction func retryButton(_ sender: UIButton) {
delegate?.retryToFetchData()
self.dismiss(animated: true, completion: nil)
}
}

我创建了一个静态函数来显示该视图。该视图只是一个UIView控制器,它将有一个子视图,该子视图将充当具有透明背景的弹出窗口。

func showErrorBox(view: UIViewController, message: String, delegate: CustomAlertViewControllerDelegate){ 
let customAlert = view.storyboard?.instantiateViewController(withIdentifier: "customAlertViewController") as! CustomAlertViewController
customAlert.providesPresentationContextTransitionStyle = true
customAlert.definesPresentationContext = true
customAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
customAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
customAlert.delegate = delegate
view.present(customAlert, animated: true, completion: nil)
}

现在,我在需要显示弹出窗口的任何地方调用此 VCshowErrorBox(view: self, message: message, delegate: self)现在我的问题是我需要在 TabBarController 内部的视图控制器中显示此弹出窗口,当我更改 UITabBar 之间的视图并尝试按重新加载按钮时,应用程序会抛出错误,

当前视图控制器不起作用:视图不在窗口中 等级制度

编辑: ErrorBox(popUp(上有一个Retry按钮。仅当加载错误框并且我将视图更改为其他选项卡然后点击重新加载按钮时,才会发生错误。在正常情况下,例如,当我在同一页面中时点击重新加载按钮可以正常工作。

我不确定问题,但它与出现错误框时更改选项卡之间的视图有关。

尝试self.present(customAlert, animated: true, completion: nil)而不是view.present(customAlert, animated: true, completion: nil)。如果我了解您的问题,应该可以工作

解决方案,

问题是,当我在 TabController 中更改视图时,对自定义警报视图的引用已从窗口层次结构中删除。因此,一旦我离开正在加载自定义警报视图的选项卡视图,就需要删除。

因此,为了解决这个问题,我在CustomAlertViewController中添加了以下代码

override func viewWillDisappear(_ animated: Bool) {
super. viewWillDisappear(animated)
self.dismiss(animated: true, completion: nil)
}

尝试获取最顶层的视图控制器并从中呈现 CustomAlertViewController 而不是"self"。

请参阅此链接: GetTopMostViewController

最新更新