將常用的功能,寫成一個方便呼叫的 function,並以 extension 的方式加在專案底下
xtension MainViewController {
/ MARK: - Alert
/// 確認、取消按鈕的 Alert
/// - Parameters:
/// - title: Alert 的標題
/// - message: Alert 的訊息
/// - vc: 要在哪個畫面跳出來
/// - confirmTitle: 確認按鈕的文字
/// - cancelTitle: 取消按鈕的文字
/// - confirm: 按下確認按鈕後要做的事
/// - cancel: 按下取消按鈕後要做的事
public func showAlertWith(title: String?, message: String?, vc: UIViewController, confirmTitle: String, cancelTitle: String, confirm: (() -> Void)?, cancel: (() -> Void)?) {
DispatchQueue.main.async {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: confirmTitle, style: .default) { action in
confirm?()
}
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { action in
cancel?()
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
vc.present(alertController, animated: true, completion: nil)
}
}
/ MARK: - NavigationController.push
/// NavigationController.pushViewController 跳頁 (不帶 Closure)
/// - Parameters:
/// - viewController: 要跳頁到的 UIViewController
/// - animated: 是否要換頁動畫,預設為 true
public func pushViewController(_ viewController: UIViewController, animated: Bool = true) {
if let navigationController = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController as? UINavigationController {
navigationController.pushViewController(viewController, animated: animated)
}
}
/// NavigationController.pushViewController 跳頁 (帶 Closure)
/// - Parameters:
/// - viewController: 要跳頁到的 UIViewController
/// - animated: 是否要換頁動畫
/// - completion: 換頁過程中,要做的事
public func pushViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) {
self.navigationController?.pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
// MARK: - NavigationController.pop
/// NavigationController.popViewController 回上一頁 (不帶 Closure)
/// - Parameters:
/// - animated: 是否要換頁動畫,預設為 true
public func popViewController(_ animated: Bool = true) {
self.navigationController?.popViewController(animated: animated)
}
/// NavigationController.popViewController 回上一頁 (帶 Closure)
/// - Parameters:
/// - animated: 是否要換頁動畫
/// - completion: 換頁過程中,要做的事
public func popViewController(animated: Bool, completion: @escaping () -> Void) {
self.navigationController?.popViewController(animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
``
這樣就大功告成啦!
可以從 GitHub - AVCaptureVideoPreviewLayerDemo 看完整的程式碼