簡體   English   中英

如何在 performSegue 的 sender 參數中傳遞閉包?

[英]How to pass a closure in performSegue's sender parameter?

在我的iOS應用程序中,我想問用戶一個問題,然后根據答案采取一些行動。

在許多其他編程框架中,我會使用模態對話框等待用戶輸入結果,然后將該結果返回給主代碼。 但是,據我所知,UIKit 框架不包含這種模態對話框 相反,我使用模態segue ,但是由於對performSegue的調用立即返回,因此編程變得有些混亂......

performSegue有一個Any?類型的發送者參數Any? . 當用戶退出 segue 時,我可以使用該參數傳遞一個包含要執行的代碼的閉包嗎? 而且,如果是這樣,如何?

我認為performSegue不可能做到這一點,但是您可以在執行 segue 時使用prepareForSegue發送值。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {        
    let vc = segue.destination as! MyViewController
    vc.myParameter = myValue

}

但如果你只是想給用戶一個對話並等待答案,還有另一種方法可以做到這一點。

您可以創建一個具有默認背景的 viewController,這將使其隱藏,然后在其中添加一個 View 並根據需要對其進行自定義,您可以將其視為警報。 然后在您想向用戶詢問數據時啟動它。

let vc = self.storyboard?.instantiateViewController(withIdentifier: "alert") as! AlertViewController
vc.definesPresentationContext = true
vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
//Here you can pass data into the viewController you're initiating
vc.myParameter = myValue
self.present(vc,animated: false,completion: nil)

這樣,您在 viewController 中自定義的 UIView 就會像當前 viewController 上的普通警報一樣出現。

在撰寫本文時,這個問題有三票反對! 我不明白為什么。 在我看來,我的問題已經清楚地說明了。

可以使用performSegueprepare(for:sender:) 但是使用instantiateViewController需要較少的設置工作。

這是基於 Yasser 回答的解決方案:

在故事板中,我創建了一個帶有半透明白色背景視圖的視圖控制器PawnPromotionVC )和一個包含“對話框”的非透明較小子視圖。 視圖控制器有一個onExit屬性聲明如下:

   var onExit : ((Piece) -> Void)?

下面是該視圖控制器中按鈕點擊的動作處理程序(順便說一下,“對話框”的目的是詢問用戶應該將一個棋子提升到哪個棋子):

  @IBAction func pieceButtonTapped(_ sender: UIButton) {
        let piece = Piece(rawValue: sender.tag)!

        if let run = onExit {
            run( piece )
        }
        dismiss(animated: true, completion: nil)
    }

要啟動我調用的對話框

  if ... {
      runPawnPromotionDialog(){
          (piece:Piece) in
           print("the pawn should be promoted to a \(piece)" )
           ...
           ...
      }
  }

從我的mainViewController 函數runPawnPromotionDialog ,也在runPawnPromotionDialog實現,幾乎按照 Yasser 的建議實現:

  func runPawnPromotionDialog( onExit: @escaping (Piece) -> Void ){

        let vc = self.storyboard?.instantiateViewController(withIdentifier: "PawnPromotionVC") as! PawnPromotionVC

        vc.definesPresentationContext = true
        vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        vc.modalTransitionStyle = .crossDissolve

        vc.onExit = onExit
        self.present(vc,animated: false,completion: nil)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM