본문 바로가기

iOS/Swift

[iOS UIKit in Swift 4] UIAlertController 사용하기 (View alerts with UIAlertController)

UIAlertController 사용하기

Show UIAlert라 써져있는 버튼을 누르게되면 AppDelegate에 만들어놓은 showAlert 함수를 통해 UIAlertController를 생성합니다.

AppDelegate에 만들어놓은 이유는 모든 ViewController에서 접근이 가능하기 때문입니다.

Title, Message, ActionButton의 Title, ActionButton의 타입 등을 정할 수 있습니다.

액션 이후의 처리가 필요하면 액션의 completion에서 처리하면 됩니다.


아래 스크린샷과 소스코드를 비교해보시면 좀 더 이해하기 편할겁니다.

궁금하신점은 댓글로 달아주세요.


해피코딩 :)


Preview


Source

//
// AlertViewController.swift
// UIKit component handling
//
// Created by Taehyeon Han on 2018. 8. 2..
// Copyright © 2018년 calmone. All rights reserved.
//
import UIKit
class AlertViewController: BaseViewController {
// Generate UIButton.
lazy var button: UIButton = {
let button: UIButton = UIButton()
let width: CGFloat = 250
let height: CGFloat = 50
let posX: CGFloat = (self.view.bounds.width - width)/2
let posY: CGFloat = 250
button.frame = CGRect(x: posX, y: posY, width: width, height: height)
button.backgroundColor = UIColor.red
button.layer.masksToBounds = true
button.layer.cornerRadius = 20.0
button.setTitle("Show UIAlert", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Add UIButton on view
self.view.addSubview(self.button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Button event
@objc private func buttonPressed(_ sender: Any) {
// This function in Appdelegate
appDelegate()?.showAlert(vc: self, title: "Title", message: "Message", actionTitle: "OK", actionStyle: .default)
}
}
//
// AppDelegate.swift
// UIKit component handling
//
// Created by Taehyeon Han on 2018. 7. 27..
// Copyright © 2018년 calmone. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
// Add UIAlertController on UIViewController
func showAlert(vc: UIViewController, title: String, message: String, actionTitle: String, actionStyle: UIAlertActionStyle) {
// Create a UIAlertController.
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Create an action of OK.
let action = UIAlertAction(title: actionTitle, style: actionStyle) { action in
print("Action OK!!")
}
// Add an Action of OK.
alert.addAction(action)
// Activate UIAlert.
vc.present(alert, animated: true, completion: nil)
}
}


Github

https://github.com/calmone/iOS-UIKit-component


Reference