2014-11-04 28 views
2

爲了管理/縮短我的代碼,我決定嘗試創建一個幫助類來管理所有警報。SWIFT - 幫助類回調

這個想法是,助手類將創建警報。當用戶按下按鈕時,它會發送回調以通知viewController上的代碼按下了哪個按鈕。然後基於此我可以激發不同的代碼。

當前我設法正確彈出警報的代碼,但是我無法在按下按鈕時發送回調。

這裏是我的警覺經理,我創建至今(仍基本爲簡單起見):

var alertMgr: alertManager = alertManager() 
class alertManager: NSObject { 

func showAlert(titleText:String?, confirmText:String, cancelText:String, msgText:String, showCancel:Bool, showConfirm:Bool, style:UIAlertControllerStyle, viewController:UIViewController) -> Int? { 


    let alertController = UIAlertController(title: titleText, message: msgText, preferredStyle: style) 
    var myInt:Int! 

    let actionLeft = UIAlertAction(title:cancelText, style: .Cancel) { action in 

     println("0") //works when user presses cancel button 
     myInt = 0 
    } 

    let actionRight = UIAlertAction(title:confirmText, style: .Default) { action in 

     println("1") //works when user presses confirm button 
     myInt = 1 
    } 

    alertController.addAction(actionLeft) 
    alertController.addAction(actionRight) 

    viewController.presentViewController(alertController, animated: true, completion: nil) 

    return myInt //does not return when button is pressed??? 
} 
} 

在我的代碼時,我想表明我使用下面的代碼警報:

 let titleTxt:String = "title txt goes here." 
     let confirmTxt:String = "confirm" 
     let cancelTxt:String = "cancel" 
     let msgTxt:String = "some msg goes here." 
     let showCancel:Bool = true 
     let showConfirm:Bool = true 
     let style:UIAlertControllerStyle = .ActionSheet 

     let alert = alertMgr.showAlert(titleTxt, confirmText: confirmTxt, cancelText: cancelTxt, msgText: msgTxt, showCancel: showCancel, showConfirm: showConfirm, style:style, viewController: self) 

     switch alert as Int! { 
      case nil: 
       println("nil value") 
      case 0: 
       println("cancel pressed") //never gets fired. when button is pressed 
      case 1: 
       println("confirm pressed") //never gets fired. when button is pressed 
      default: 
       break 
     } 

主要的問題是我似乎無法接到回撥,按下按鈕發送「myInt」值。我已經通過[UIAlertController]搜索了很多關於這個問題的所有問題,並且一直沒有找到任何提示將我推向正確方向的提示。

任何幫助將是偉大的。

回答

2

showAlert返回值myInt在任何給定的塊有機會執行之前,解決方法是傳遞完整的動作塊作爲參數showAlert。爲了縮短簽名,您可以使用文本,塊和標記值準備特殊類型,並使該函數處理此類對象的數組。

+0

謝謝你的回覆。我不是100%確定,我明白,你可以請張貼一個示例代碼,以更好地幫助我理解?同時,我會繞過,看看我能否弄清楚。謝謝:) – 2014-11-05 11:40:35

+0

當用戶按下按鈕時,會調用「actionLeft」和「actionRight」塊,但函數showAlert立即返回 - 您可以刪除返回值,因爲它沒用。相反,您可以使用'UIAlertAction'類型的兩個參數來替換'actionLeft'和'actionRight'請注意,塊和閉包之間有區別,您可以在官方文檔中閱讀更多內容,無論如何,方法是相同的。您可以使用任何帶有閉包的標準方法作爲函數/閉包原型的示例,例如'UIView + animateWithDuration:delay:options:animations:completion: ' – 2014-11-05 13:13:23

+0

我想我可能會有點困惑。因此,在我從showAlert中刪除返回後,並用兩個UIAlertAction參數替換actionLeft/actionRight。 VC的回調在哪裏發生?(因此,我可以根據確認/取消激活下一個代碼)感覺有點失落。 PS ....我讀了更多關於塊/關閉。但仍然沒有看到這100% – 2014-11-05 21:00:46