呈现UIAlertViewController投掷"查看不在窗口heirarchy" - 斯威夫特

时间:2016-02-18 02:14:42

标签: ios iphone swift

首先,我不是用viewDidLoad()方法调用它。它是ViewController类中自己的方法,它呈现Alert。

我构建了一个UIView的实例。在该视图类中有一个按钮,当按下该按钮时,调用视图控制器方法来显示警报(因为苹果决定这些需要是视图控制器)。

但是,当调用该方法时,它会抛出典型的"视图而不是窗口层次结构"警告。

视图控制器:

let feedVC: FeedViewController = FeedViewController()

class FeedViewController: UIViewController {
    override func viewDidLoad() {
        //stuff happens
    }

    override func viewDidAppear() {
        //here is where i build the views and display them
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let returned = feedMngr.retrieveFeed()

        if (returned) {
            dispatch_async(dispatch_get_main_queue()) {
                self.constructFeedStack()
                self.view.addSubview(self.firstCardView!)
                self.view.insertSubview(self.secondCardView!, belowSubview: self.firstCardView!)
                self.view.insertSubview(self.thirdCardView!, belowSubview: self.secondCardView!)
                self.view.insertSubview(self.fourthCardView!, belowSubview: self.thirdCardView!)
            }
        }
    }

    func throwFlagAlert() {
        NSLog("throwing flag alert")
        // set up the alert controller here
        let alert = UIAlertController(title: "Flag Content",
            message: "Do you wish to flag this post as offensive?",
            preferredStyle: UIAlertControllerStyle.Alert)

        // Cancel action
        //   nil handler means "no action if Cancel button selected"
        alert.addAction(UIAlertAction(title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler: nil))

        // Confirm action
        alert.addAction(UIAlertAction(title: "Flag",
            style: UIAlertActionStyle.Default,
            handler: nil))

        self.presentViewController(alert, animated: true, completion: nil)

    }
 }

UIView中调用此方法的函数:

func flagContent(sender: UIButton!) {
    //feedVC is the global instance of the view controller
    //it's the only way I could think to access the VC from within the view
    feedVC.throwFlagAlert(feedVC)
}

编辑:已解决 因此,遇到这种挫败感的其他人可能会知道: 答案是在viewDidAppear()中执行以下操作:

feedVC = self

2 个答案:

答案 0 :(得分:1)

所以遇到这种挫败感的人可能会知道: 答案是在viewDidAppear()中执行以下操作:

feedVC = self

答案 1 :(得分:0)

将您的代码放入dispatch_async块,然后尝试显示警报控制器。

这对我有用。