반응형
프로젝트를 진행하다보면 여러부분이 중복되어 들어가는 경우가 많이 생긴다.
그 중에서도 가장 많이 사용하는 함수 중 하나가 Alert을 생성하는 함수이지 않을까 싶다.
class Common{
/// 금액에 , 찍어 리턴해주는 함수
func formatPrice(n: Int) -> String{
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
return numberFormatter.string(from: NSNumber(value: n)) ?? "\(n)"
}
/// Alert 호출 함수
func showAlert(message: String, buttonTitle: String, buttonClickTitle: String) {
let alert = UIAlertController(title: buttonTitle, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonClickTitle, style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
그리하여 이번에 공용함수를 만들어 사용해보려 하는데 인자를 받아서 실행을 Alert을 만드는 함수를 만들었더니 에러가 나고있다.
가장 문제가 되는문제는 present이다.
우리가 화면전환에 사용하는 present의 경우에는 UIViewController의 상속을 받아야 사용이 가능하다.
그런데 공용함수에서는 UIViewController을 상속받지 않은 것이다.
import Foundation
import UIKit
class Common{
/// 금액에 , 찍어 리턴해주는 함수
func formatPrice(n: Int) -> String{
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
return numberFormatter.string(from: NSNumber(value: n)) ?? "\(n)"
}
}
extension UIViewController {
/// Alert 호출 함수
func showAlert(message: String, buttonTitle: String, buttonClickTitle: String) {
let alert = UIAlertController(title: buttonTitle, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonClickTitle, style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
/// 동기처리 Alert함수
func showSnycAlert(message: String, buttonTitle: String, buttonClickTitle: String, method: @escaping () -> Void) {
let alert = UIAlertController(title: buttonTitle, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonClickTitle, style: .default, handler: { _ in
method()
}))
present(alert, animated: true, completion: nil)
}
}
이후 extension으로 확장을 진행한 다음에 선언을 진행해 주었다.
하는 김에
우리가 간혹 alert의 버튼을 클린 한 후에 로직이 진행되어야하는 부분이 생기는데
그 부분을 showSnycAlert(동기화 alert)을 만들어 보았다.
파라미터로는 method를 한번 더 받으면 되는것 이고
호출 시에는
showSnycAlert(message: "이미 같은 책이 담겨져 있습니다.", buttonTitle: "확인", buttonClickTitle: "OK"){
return <-- 버튼이 눌리고 난 후 실행되어야 하는 로직
}
이런식으로 진행을 하면 됩니다.
반응형
'Ios > Swift' 카테고리의 다른 글
[이론] iOS면접 대비 질문 준비 1 (0) | 2024.09.03 |
---|---|
[Swift] CollectionView에 대한 끄적임 (0) | 2024.08.07 |
[Swift] MVVM에 대한 끄적임.. (0) | 2024.08.01 |
[Swift] 자주 쓰이는 RxSwift의 개념 (0) | 2024.07.31 |
[Swift] Xcode Instruments에 대한 끄적임 (0) | 2024.07.30 |