警告:尝试在<...>上呈现<UIAlertController:0x7facd3946920>已经呈现(null)

Mor*_*Man 21 uitableview ios swift uialertcontroller

我有一个长按手势一组UITableView呈现一个UIAlertController包含单元格的文本.当UIAlertController提出时,我得到这个警告:

Attempt to present <UIAlertController: 0x7fd57384e8e0>  on <TaskAppV2.MainTaskView: 0x7fd571701150> which is already presenting (null)
Run Code Online (Sandbox Code Playgroud)

根据我的理解,MainTaskView(UITableView)已经呈现了一个视图,因此它不应该呈现第二个视图,UIAlertController.所以我从类似的问题尝试了这个解决方案.它不起作用,因为我收到相同的警告.我该怎么做才能解决这个警告?请参阅下面的代码:

func longPressedView(gestureRecognizer: UIGestureRecognizer){

    /*Get cell info from where user tapped*/
    if (gestureRecognizer.state == UIGestureRecognizerState.Ended) {
        var tapLocation: CGPoint = gestureRecognizer.locationInView(self.tableView)

        var tappedIndexPath: NSIndexPath? = self.tableView.indexPathForRowAtPoint(tapLocation)
        if (tappedIndexPath != nil) {
            var tappedCell: UITableViewCell? = self.tableView.cellForRowAtIndexPath(tappedIndexPath!)
            println("the cell task name is \(tappedCell!.textLabel!.text!)")
        } else {
            println("You didn't tap on a cell")
        }
    }

    /*Long press alert*/
    let tapAlert = UIAlertController(title: "Long Pressed", message: "You just long pressed the long press view", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    /*
    if (self.presentedViewController == nil) {
        self.presentViewController(tapAlert, animated: true, completion: nil)
    } else {
        println("already presenting a view")
    } */

    self.presentViewController(tapAlert, animated: true, completion: nil)
    println("presented")
}
Run Code Online (Sandbox Code Playgroud)

控制台输出:

presented
You didn't tap on a cell
2015-05-19 22:46:35.692 TaskAppV2[60765:3235207] Warning: Attempt to present <UIAlertController: 0x7fc689e05d80>  on <TaskAppV2.MainTaskView: 0x7fc689fc33f0> which is already presenting (null)
presented
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当长按手势发生时,两条代码都在if语句中执行.将显示警报,并将文本打印到控制台.这是一个问题吗?

编辑:正如马特所说,我没有把我的所有代码都放在手势识别器测试的范围内.移动它解决我的问题.测试之外的代码被执行了两次,导致UIAlertController被呈现两次.

mat*_*att 18

出于某种原因,两段代码都在执行 if

那对我来说应该响起警钟.它if和它们都不可能else运行.此代码必须运行两次.

那是因为您没有测试手势识别器的状态.长按gr发送其动作消息两次.您在长按和发布时都运行此代码.您需要测试gr的状态,以便不要这样做.例:

@IBAction func longPressedView(g: UIGestureRecognizer) {
    if g.state == .Began {
        // ... do it all here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 天才!我在`presentViewController`下放了一个`println()`,每按一次就会执行两次. (2认同)

Dmi*_*nko 12

我有同样的问题.我能够通过这段代码修复它:

        if self.presentedViewController == nil {
            self.present(Alert, animated: true, completion: nil)
        }
        else {
            self.dismiss(animated: false, completion: nil)
            self.present(Alert, animated: true, completion: nil)
        }
Run Code Online (Sandbox Code Playgroud)

  • 将第二个存在于第二个解除完成处理程序中. (2认同)