import UIKit
extension UIViewController {
/// [UIViewController+] 画面のスクリーンショットを取る
func e_screenshotFromWindow(scale: CGFloat = 0.0) -> UIImage? {
guard let window = UIApplication.sharedApplication().windows.first else {
return nil
}
UIGraphicsBeginImageContextWithOptions(window.frame.size, false, scale)
window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
★ UIAlertControllerを拡張
extension UIViewController {
// 1つボタンのアラートを生成
func oneButtonAlert(title : String = nil,
message: String = nil,
button : String = nil,
handler: @escaping () -> ()) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action1 = UIAlertAction(title: button, style: .default, handler: { action in
handler()
})
alert.addAction(action1)
present(alert, animated: true, completion: nil)
}
// 2つボタンのアラートを生成
func twoButtonAlert(title : String = nil,
message : String = nil,
button1 : String = nil,
button2 : String = nil,
handler1: @escaping () -> (),
handler2: @escaping () -> ()) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action1 = UIAlertAction(title: button1, style: .default, handler: { action in
handler1()
})
let action2 = UIAlertAction(title: button2, style: .default, handler: { action in
handler2()
})
alert.addAction(action1)
alert.addAction(action2)
present(alert, animated: true, completion: nil)
}
}
// Usage
VC.oneButtonAlert(title: "Title",
message: "Message",
button: "OK") {
// Button Tap Event
}
- 全てのModal画面を閉じる
import UIKit
class TopViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func dismiss(_ sender: UIButton) {
// 全てのモーダルを閉じる
dismissAll(animated: true) {
}
}
}
extension UIViewController {
func dismissAll(animated: Bool, completion: (() -> Void)?) {
var presentingViewController = UIApplication.shared.topViewController?.presentingViewController
guard let _ = presentingViewController?.presentingViewController else {
completion?()
return
}
while let presenting = presentingViewController?.presentingViewController {
presentingViewController = presenting
}
presentingViewController?.dismiss(animated: animated, completion: {
completion?()
})
}
}
extension UIApplication {
var topViewController: UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while let presentedViewController = topViewController.presentedViewController {
topViewController = presentedViewController
}
return topViewController
}
}