import UIKit
class TestVeiwcontroller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
}
//최상단 뷰에서 얼럿을 그릴 수 있으니까 뷰가 다 만들어진 다음 호출 가능
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
testalert()
}
// nil뱉는 메서드
func testalert() {
let test: String? = nil
if test == nil {
test.alert() // 현재 test의 타입은 옵셔널 string이니까 Enum에서 만들어준 alert에 접근 가능
}
}
}
extension Optional {
func alert() {
switch self {
case .none:
guard let viewcontroller = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController?.topViewController else { return }
let alert = UIAlertController(title: "이건 테스트 얼럿입니다", message: "테스틍입니당", preferredStyle: .alert)
let ok = UIAlertAction(title: "ok", style: .default)
alert.addAction(ok)
// 뷰에서 띄워줘야하니까 탑뷰를 설정해줘야함
viewcontroller.present(alert, animated: true)
case .some(let wrapped):
print("값이 있꿍요!")
}
}
}
// 탑뷰 인식하는 익스퉨숀
extension UIViewController {
//현재 뷰를 취상단뷰로 설정해줌
var topViewController: UIViewController? {
return self.topViewController(currtentViewController: self)
}
func topViewController(currtentViewController: UIViewController) -> UIViewController {
if let tabBarController = currtentViewController as? UITabBarController, let selectedViewController = tabBarController.selectedViewController {
return self.topViewController(currtentViewController: selectedViewController)
} else if let navigationController = currtentViewController as? UINavigationController, let visibleViewController = navigationController.visibleViewController {
return self.topViewController(currtentViewController: visibleViewController)
} else if let presentedViewController = currtentViewController.presentedViewController {
return self.topViewController(currtentViewController: presentedViewController)
} else {
return currtentViewController
}
}
}
옵셔널 이넘 읽다가 써봤따
언제 쓸깡.
중요한건 아니니 결과물이 궁금하면 아래 보시면 됨다
런 -> 뷰가 뜸과 동시에 얼럿 뜸