Menu
Menu

UITextFieldAlert

입력할 수 있는 Alert창이 필요해서 뚝딱 하나 만들었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func createTextFieldAlert(title: String?, previousText: String? = nil, completion: @escaping (String) -> Void) -> UIAlertController{
let alert = UIAlertController(
title: title,
message: nil,
preferredStyle: .alert)

let okAction = UIAlertAction(
title: "OK",
style: .default
) { [unowned alert] _ in
let text = alert.textFields![0].text
// do something interesting with "answer" here
LogHelper.printLog("text : \(text)")
completion(text ?? "")
}

alert.addTextField { textField in
textField.text = previousText
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
LogHelper.printLog("containsEmoji : \((textField.text ?? "").containsEmoji)")
guard let inputText = textField.text else {
okAction.isEnabled = false
return
}

okAction.isEnabled = !inputText.containsEmoji && inputText.count > 1 && previousText != inputText
}
}

okAction.isEnabled = false

alert.addAction(okAction)
alert.addAction(UIAlertAction.cancelAction())
return alert
}

사용법은 아래와같다 :)

1
2
3
4
5
6
UIAlertController.createTextFieldAlert(
title: "변경할 닉네임을 입력해 주세요.",
previousText: "UserInformationManager.shared.userInfo?.displayName"
) { [weak self] name in
LogHelper.printLog("name : \(name)")
}.show()