iOS8之後蘋果添加了 UIAlertContoller 來替代 UIAlertView與UIActionSheet
我們首先介紹在 swift 中怎麼使用 UIAlertController
UIAlertController 初始化 let alertController: UIAlertController = UIAlertController (title: “ 我是 标題君 " , message: " 要優雅 " , preferredStyle: . Alert ) 最後設定彈框類型的參數 有兩個值 . ActionSheet 底部框 . Alert 警告框 ps:兩種類型彈框用法相同
初始化标簽動作 let alertAction:UIAlertAction = UIAlertAction(title: "買買買", style: .Default, handler: { (action:UIAlertAction) -> Void in print ( “錢包生命值-999 " ) }) alertController . addAction (alertAction) 參數style設定标簽風格有三種(級别) .Default 預設 .Cancel 取消 .Destructive 警示(紅色字型) let alertAction2 : UIAlertAction = UIAlertAction (title: “我選擇死亡 " , style: . Cancel , handler: { (action: UIAlertAction ) -> Void in print ( "我不會就這樣輕易的狗帶 " ) }) alertController . addAction ( alertAction2 ) let alertAction3 : UIAlertAction = UIAlertAction (title: 崩!啥卡拉卡! " , style: . Destructive , handler: { (action: UIAlertAction ) -> Void in print ( “恭喜玩家,你媽炸了 " ) }) alertController . addAction ( alertAction3 ) 模态推出視圖 self.presentViewController( alertController , animated: true, completion: { () -> Void in print ( " 就是彈個框,别害怕,我不是什麼好人 " ) }) 按鈕如果達到3個或三個以上,會成一列顯示。如果少于3個,則成一排顯示。
那麼問題來了,如何添加文字輸入框呢(雖然我完全沒在實踐中用到過) alert. addTextFieldWithConfigurationHandler ({ (textField: UITextField ) -> Void in textField. placeholder = “我是帳号君 " }) alert.addTextFieldWithConfigurationHandler ({ ( textField: UITextField ) -> Void in textField. placeholder = “我是密碼君 " textField. secureTextEntry = true // 密碼模式 })
由于很多公司還相容低版本(例如我們公司,之前相容到 ios6.最近改為相容到 ios7)是以 alertView 與 alertController 并用在所難免,github 上有封裝的比較好的庫,可以省去我們重複寫大量代碼的問題,swift不知道有沒有,不過已經在 swift 的公司,應該不會相容到低版本了,是以講道理大概不存在此問題。
老舊的 UIAlertView 與 OC 一樣,先初始化 uialertViewDelegate let alertView = UIAlertView (title: <#T##String#>, message: <#T##String#>, delegate: <#T##UIAlertViewDelegate?#>, cancelButtonTitle: <#T##String?#>, otherButtonTitles: <#T##String#>, <#T##moreButtonTitles: String...##String#>) alertView.show() 實作代理方法 func alertView(alertView: UIAlertView , didDismissWithButtonIndex buttonIndex: Int ) { }
UIActionSheet也與 OC 相同。