UIViewController+Extension.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. //
  2. // UIViewController+Extension.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2018/4/9.
  6. // Copyright © 2018年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import Chrysan
  10. extension UIViewController {
  11. ///EZSE: Pushes a view controller onto the receiver’s stack and updates the display.
  12. open func pushVC(_ vc: UIViewController) {
  13. navigationController?.pushViewController(vc, animated: true)
  14. }
  15. ///EZSE: Pops the top view controller from the navigation stack and updates the display.
  16. open func popVC() {
  17. _ = navigationController?.popViewController(animated: true)
  18. }
  19. /// EZSE: Added extension for popToRootViewController
  20. open func popToRootVC() {
  21. _ = navigationController?.popToRootViewController(animated: true)
  22. }
  23. ///EZSE: Presents a view controller modally.
  24. open func presentVC(_ vc: UIViewController) {
  25. present(vc, animated: true, completion: nil)
  26. }
  27. ///EZSE: Dismisses the view controller that was presented modally by the view controller.
  28. open func dismissVC(completion: (() -> Void)? ) {
  29. dismiss(animated: true, completion: completion)
  30. }
  31. func setNavRightBarItemsTextDefault() {
  32. if let rightItems = self.navigationItem.rightBarButtonItems {
  33. for item in rightItems {
  34. item.setTitleTextAttributes([NSAttributedString.Key.font : UIFont(name: "PingFangTC-Regular", size: 14)!], for: .normal)
  35. }
  36. }
  37. }
  38. func setNavLeftBarItemsTextDefault() {
  39. if let leftItems = self.navigationItem.leftBarButtonItems {
  40. for item in leftItems {
  41. item.setTitleTextAttributes([NSAttributedString.Key.font : UIFont(name: "PingFangTC-Regular", size: 14)!], for: .normal)
  42. }
  43. }
  44. }
  45. func forwardDestVC(_ storyBoardName:String,_ destVCIdentitifer:String?){
  46. let window = UIApplication.shared.keyWindow
  47. let storyBoard:UIStoryboard = UIStoryboard.init(name: storyBoardName, bundle: nil)
  48. var destVC:UIViewController!
  49. if destVCIdentitifer != nil {
  50. destVC = storyBoard.instantiateViewController(withIdentifier: destVCIdentitifer!)
  51. }else{
  52. destVC = storyBoard.instantiateInitialViewController()
  53. }
  54. window?.rootViewController = destVC
  55. window?.makeKeyAndVisible()
  56. }
  57. func forwardDestVC(_ targetVC:UIViewController){
  58. let window = UIApplication.shared.keyWindow
  59. window?.rootViewController = targetVC
  60. window?.makeKeyAndVisible()
  61. }
  62. func getDestVC<T>(vcType:T.Type,storyBoardName:String,identitiferController:String?) -> T {
  63. let storyBoard = UIStoryboard(name: storyBoardName, bundle: nil)
  64. var destVC:T
  65. if let identitifer = identitiferController {
  66. destVC = storyBoard.instantiateViewController(withIdentifier: identitifer) as! T
  67. }else{
  68. destVC = storyBoard.instantiateInitialViewController() as! T
  69. }
  70. return destVC
  71. }
  72. }
  73. // MARK:- AlertController
  74. extension UIViewController {
  75. /// 系统弹出框确认
  76. ///
  77. /// - Parameters:
  78. /// - title: 标题
  79. /// - message: 提示消息
  80. /// - okHandler: 确定行为
  81. func showDefaultConfirm(title: String, message: String, okHandler: @escaping ((UIAlertAction) -> Void)) {
  82. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  83. let okAction = UIAlertAction(title: "确定", style: .default, handler: okHandler)
  84. let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
  85. alertController.addAction(okAction)
  86. alertController.addAction(cancelAction)
  87. self.present(alertController, animated: true, completion: nil)
  88. }
  89. func showDefaultConfirm(title: String, message: String, okAction: UIAlertAction, cancelAction: UIAlertAction) {
  90. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  91. alertController.addAction(okAction)
  92. alertController.addAction(cancelAction)
  93. self.present(alertController, animated: true, completion: nil)
  94. }
  95. /// 系统弹出框提示
  96. ///
  97. /// - Parameters:
  98. /// - title: 标题
  99. /// - message: 提示消息
  100. /// - okHandler: 确定行为
  101. func showSystemAlert(title: String, message: String, okHandler: @escaping ((UIAlertAction) -> Void)) {
  102. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  103. let okAction = UIAlertAction(title: "确定", style: .default, handler: okHandler)
  104. alertController.addAction(okAction)
  105. self.present(alertController, animated: true, completion: nil)
  106. }
  107. func showSystemAlertWithButtonName(title: String, message: String, buttonName: String, okHandler: @escaping ((UIAlertAction) -> Void)) {
  108. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  109. let okAction = UIAlertAction(title: buttonName, style: .default, handler: okHandler)
  110. alertController.addAction(okAction)
  111. self.present(alertController, animated: true, completion: nil)
  112. }
  113. // actionSheet 形式的弹出提示框 可以传入多个Action 已经有取消Action了
  114. func showSheetAction(title: String?, message: String?, actions: [UIAlertAction]) {
  115. let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
  116. actions.forEach { (action) in
  117. alertController.addAction(action)
  118. }
  119. let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
  120. alertController.addAction(cancelAction)
  121. self.present(alertController, animated: true, completion: nil)
  122. }
  123. //actionSheet 传入的actions需要包含取消Action
  124. func showActionSheetIncludeCancelBtn(title: String?, message: String?, actions: [UIAlertAction]) {
  125. let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
  126. actions.forEach { (action) in
  127. alertController.addAction(action)
  128. }
  129. self.present(alertController, animated: true, completion: nil)
  130. }
  131. func datePickerTapped(_ title:String,_ dateType:UIDatePicker.Mode,_ format:String,callBackResult:((_ result:Date) -> Void)?) {
  132. let locale = Locale(identifier: "zh")
  133. let theDate = Date()
  134. var dateComponents = DateComponents()
  135. dateComponents.month = -12
  136. let threeMonthAgo = Calendar.current.date(byAdding: dateComponents, to: theDate)
  137. dateComponents.month = 12
  138. let nextYearMonthAgo = Calendar.current.date(byAdding: dateComponents, to: theDate)
  139. let datePicker = LWDatePickerDialog(textColor: .red,
  140. buttonColor: .red,
  141. font: UIFont.boldSystemFont(ofSize: 17),
  142. locale:locale ,
  143. showCancelButton: true)
  144. datePicker.show(title,
  145. doneButtonTitle: "确定",
  146. cancelButtonTitle: "取消",
  147. defaultDate: theDate,
  148. minimumDate: threeMonthAgo,
  149. maximumDate: nextYearMonthAgo,
  150. datePickerMode: dateType) { (date) in
  151. if let dt = date {
  152. let formatter = DateFormatter()
  153. formatter.dateFormat = format
  154. let _ = formatter.string(from: dt)
  155. if let block = callBackResult {
  156. block(dt)
  157. }
  158. }
  159. }
  160. }
  161. }
  162. // MARK:- ProgressHUD
  163. extension UIViewController {
  164. func showSuccess(title:String) {
  165. DispatchQueue.main.async {
  166. self.chrysan.show(.succeed, message: title, hideDelay: 1)
  167. }
  168. }
  169. func showError(title:String){
  170. DispatchQueue.main.async {
  171. self.chrysan.show(.error, message: title, hideDelay: 1)
  172. }
  173. }
  174. func showLoading(title:String){
  175. DispatchQueue.main.async {
  176. self.chrysan.show(.running, message: title)
  177. }
  178. }
  179. func showLoading() {
  180. DispatchQueue.main.async {
  181. self.chrysan.show()
  182. }
  183. }
  184. func hideLoading() {
  185. DispatchQueue.main.async {
  186. self.chrysan.hide()
  187. }
  188. }
  189. }
  190. // MARK:- 加动画退出app
  191. extension UIViewController {
  192. func exitAPP() {
  193. let appDelegate = UIApplication.shared.delegate!
  194. let window = appDelegate.window!
  195. UIView.animate(withDuration: 0.4, animations: {
  196. UIView.animate(withDuration: 0.4) {
  197. window?.alpha = 0
  198. let y = window?.bounds.size.height
  199. let x = (window?.bounds.size.width)! / 2
  200. window?.frame = CGRect(x: x, y: y!, width: 0, height: 0)
  201. }
  202. }) { (completed) in
  203. exit(0)
  204. }
  205. }
  206. }
  207. //MARK: -
  208. extension UIViewController {
  209. ///EZSE: Adds an NotificationCenter with name and Selector
  210. open func addNotificationObserver(_ name: String, selector: Selector) {
  211. NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
  212. }
  213. ///EZSE: Removes an NSNotificationCenter for name
  214. open func removeNotificationObserver(_ name: String) {
  215. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil)
  216. }
  217. ///EZSE: Removes NotificationCenter'd observer
  218. open func removeNotificationObserver() {
  219. NotificationCenter.default.removeObserver(self)
  220. }
  221. ///EZSE: Adds a NotificationCenter Observer for keyboardWillShowNotification()
  222. ///
  223. /// ⚠️ You also need to implement ```keyboardWillShowNotification(_ notification: Notification)```
  224. open func addKeyboardWillShowNotification() {
  225. self.addNotificationObserver(UIResponder.keyboardWillShowNotification.rawValue, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
  226. }
  227. ///EZSE: Adds a NotificationCenter Observer for keyboardDidShowNotification()
  228. ///
  229. /// ⚠️ You also need to implement ```keyboardDidShowNotification(_ notification: Notification)```
  230. public func addKeyboardDidShowNotification() {
  231. self.addNotificationObserver(UIResponder.keyboardDidShowNotification.rawValue, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
  232. }
  233. ///EZSE: Adds a NotificationCenter Observer for keyboardWillHideNotification()
  234. ///
  235. /// ⚠️ You also need to implement ```keyboardWillHideNotification(_ notification: Notification)```
  236. open func addKeyboardWillHideNotification() {
  237. self.addNotificationObserver(UIResponder.keyboardWillHideNotification.rawValue, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
  238. }
  239. ///EZSE: Adds a NotificationCenter Observer for keyboardDidHideNotification()
  240. ///
  241. /// ⚠️ You also need to implement ```keyboardDidHideNotification(_ notification: Notification)```
  242. open func addKeyboardDidHideNotification() {
  243. self.addNotificationObserver(UIResponder.keyboardDidHideNotification.rawValue, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
  244. }
  245. ///EZSE: Removes keyboardWillShowNotification()'s NotificationCenter Observer
  246. open func removeKeyboardWillShowNotification() {
  247. self.removeNotificationObserver(UIResponder.keyboardWillShowNotification.rawValue)
  248. }
  249. ///EZSE: Removes keyboardDidShowNotification()'s NotificationCenter Observer
  250. open func removeKeyboardDidShowNotification() {
  251. self.removeNotificationObserver(UIResponder.keyboardDidShowNotification.rawValue)
  252. }
  253. ///EZSE: Removes keyboardWillHideNotification()'s NotificationCenter Observer
  254. open func removeKeyboardWillHideNotification() {
  255. self.removeNotificationObserver(UIResponder.keyboardWillHideNotification.rawValue)
  256. }
  257. ///EZSE: Removes keyboardDidHideNotification()'s NotificationCenter Observer
  258. open func removeKeyboardDidHideNotification() {
  259. self.removeNotificationObserver(UIResponder.keyboardDidHideNotification.rawValue)
  260. }
  261. @objc open func keyboardDidShowNotification(_ notification: Notification) {
  262. if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
  263. let frame = value.cgRectValue
  264. keyboardDidShowWithFrame(frame)
  265. }
  266. }
  267. @objc open func keyboardWillShowNotification(_ notification: Notification) {
  268. if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
  269. let frame = value.cgRectValue
  270. keyboardWillShowWithFrame(frame)
  271. }
  272. }
  273. @objc open func keyboardWillHideNotification(_ notification: Notification) {
  274. if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
  275. let frame = value.cgRectValue
  276. keyboardWillHideWithFrame(frame)
  277. }
  278. }
  279. @objc open func keyboardDidHideNotification(_ notification: Notification) {
  280. if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
  281. let frame = value.cgRectValue
  282. keyboardDidHideWithFrame(frame)
  283. }
  284. }
  285. @objc open func keyboardWillShowWithFrame(_ frame: CGRect) {
  286. }
  287. @objc open func keyboardDidShowWithFrame(_ frame: CGRect) {
  288. }
  289. @objc open func keyboardWillHideWithFrame(_ frame: CGRect) {
  290. }
  291. @objc open func keyboardDidHideWithFrame(_ frame: CGRect) {
  292. }
  293. //EZSE: Makes the UIViewController register tap events and hides keyboard when clicked somewhere in the ViewController.
  294. open func hideKeyboardWhenTappedAround(cancelTouches: Bool = false) {
  295. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
  296. tap.cancelsTouchesInView = cancelTouches
  297. view.addGestureRecognizer(tap)
  298. }
  299. //EZSE: Dismisses keyboard
  300. @objc open func dismissKeyboard() {
  301. view.endEditing(true)
  302. }
  303. ///跳转到应用设置页面
  304. ///
  305. /// - Parameter alertMessage: 确认提示消息,如果是nil就直接跳转
  306. func gotoApplicationSettings(alertMessage:String? = nil) {
  307. if alertMessage != nil {
  308. showDefaultConfirm(title: "提示", message: alertMessage!, okHandler: { (okAction) in
  309. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
  310. })
  311. }else {
  312. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
  313. }
  314. }
  315. }