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

我在UITableView上设置了一个长按手势,提供了一个包含单元格文本的UIAlertController 。 当UIAlertController出现时,我得到这个警告:

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

从我的理解,MainTaskView( UITableView )已经呈现一个视图,所以它不应该提供第二个视图, UIAlertController. 所以我从类似的问题尝试了这个解决scheme。 它不起作用,因为我得到相同的警告。 我能做些什么来解决这个警告? 请参阅下面的代码:

 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") } 

控制台输出:

 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 

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

编辑:正如马特所说,我没有在手势识别器testing范围内的所有我的代码。 移动,以解决我的问题。 testing之外的代码被执行两次,导致UIAlertController被呈现两次。

由于某些原因,这两个代码段都在if中执行

对我来说应该有敲响的警钟。 ifelse都不可能运行。 此代码必须运行两次。

那是因为你没有testing手势识别器的状态 。 长按gr会发送两次动作信息。 您在长按和发布时都运行此代码。 你需要testinggr的状态,这样你才不会这样做。 例:

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

我有同样的问题。 我能够解决这个代码:

  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) } 

你应该区分手势状态然后执行你想要的代码,如果不是你添加到目标的select器将在手势的状态是UIGestureRecognizerStateBegan时第一次被执行,并且第二次当手势的状态是UIGestureRecognizerStateCancelled ,第二次执行alertController显示,所以Xcode会logging警告。