Swift의 UIAlert Controller에 TextField를 추가하는 방법
저는 보여주려고 노력하고 있습니다.UIAlertController와 함께UITextView줄을 추가할 때:
//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
}
나는Runtime오류:
치명적 오류: 선택적 값의 래핑을 해제하는 동안 예기치 않게 0이(가) 발견되었습니다.
let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)
//cancel button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
//Create an optional action
let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
let text = (alertController.textFields?.first as! UITextField).text
println("You entered \(text)")
}
alertController.addAction(nextAction)
//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.textColor = UIColor.greenColor()
}
//Present the AlertController
presentViewController(alertController, animated: true, completion: nil)
이것은 내 안에 제시되어 있습니다.ViewController경유로IBAction.
나는 여기서 코드를 다운로드했고 그것은 잘 작동합니다.저는 그 방법을 복사해서 제 코드에 붙여넣었고 그것은 깨졌습니다.마지막 줄에 자신의 존재는 영향을 미치지 않습니다.
스위프트 5.1
alert.addTextField { (textField) in
textField.placeholder = "Enter First Name"
}
이 코드를 사용하십시오. 앱에서 이 코드를 성공적으로 실행하고 있습니다.
@IBAction func addButtonClicked(sender : AnyObject){
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Second Name"
}
let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
(action : UIAlertAction!) -> Void in })
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter First Name"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
편집: Swift 3.0 버전
@IBAction func addButtonClicked(_ sender: UIButton){
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Second Name"
}
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
print("firstName \(firstTextField.text), secondName \(secondTextField.text)")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in })
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter First Name"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
Swift 3.0에서 텍스트 필드 추가하기
let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
let textField = alertController.textFields![0] as UITextField
// do something with textField
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
textField.placeholder = "Search"
})
self.present(alertController, animated: true, completion: nil)
솔루션:
스위프트 4.2
다음 행을 사용하여 작동하는지 확인합니다.
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Second Name"
}
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter First Name"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
도움이 되길 바랍니다.
그래서 저는 제 코드와 작동 코드가 무엇이 다를 수 있는지 확인하기 시작했습니다.View 컨트롤러가 확장됨을 확인했습니다.
UITextFieldDelegate
즉, 하위 UITextView의 대리자를 설정해야 합니다.
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
searchTextField = textField
searchTextField?.delegate = self //REQUIRED
searchTextField?.placeholder = "Enter your search terms"
}
알림 보기에 textField를 추가하는 방법은 무엇입니까?짧고 간단하게 합시다.
이것은 Swift 3.0 이상에서 작동합니다.
var nameField: UITextField?
let alertController = UIAlertController(title: "Add Number", message: nil, preferredStyle: .alert)
// Add textfield to alert view
alertController.addTextField { (textField) in
nameField = textField
}
먼저 다음의 객체를 인스턴스화합니다.UIAlertController그런 다음 액세스하여 텍스트 필드를 추가합니다.addTextField의 일원UIAlertController학급.
UIAlertController와 함께UITextfield최신 Apple Swift 버전 5.1.3에서
작성lazy 의 변수.UIAlertController당신의UIViewController,더하다UITextFieldDelegate경고 표시 날짜UIButton작업:
class YourViewController: UIViewController,UITextFieldDelegate {
//Create Alert Controller Object here
lazy var alertEmailAddEditView:UIAlertController = {
let alert = UIAlertController(title:"My App", message: "Customize Add/Edit Email Pop Up", preferredStyle:UIAlertController.Style.alert)
//ADD TEXT FIELD (YOU CAN ADD MULTIPLE TEXTFILED AS WELL)
alert.addTextField { (textField : UITextField!) in
textField.placeholder = "Enter emails"
textField.delegate = self
}
//SAVE BUTTON
let save = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { saveAction -> Void in
let textField = alert.textFields![0] as UITextField
print("value entered by user in our textfield is: \(textField.text)")
})
//CANCEL BUTTON
let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
(action : UIAlertAction!) -> Void in })
alert.addAction(save)
alert.addAction(cancel)
return alert
}()
//MARK:- UIButton Action for showing Alert Controller
@objc func buttonClicked(btn:UIButton){
self.present(alertEmailAddEditView, animated: true, completion: nil)
}
//MARK:- UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
해피 코딩!! :)
textField가 하나인 alertController를 추가하려면(Swift 5)
func openAlert(){
let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter name"
}
let saveAction = UIAlertAction(title: kAlertConfirm, style: .default, handler: { alert -> Void in
if let textField = alertController.textFields?[0] {
if textField.text!.count > 0 {
print("Text :: \(textField.text ?? "")")
}
}
})
let cancelAction = UIAlertAction(title: kAlertCancel, style: .default, handler: {
(action : UIAlertAction!) -> Void in })
alertController.addAction(cancelAction)
alertController.addAction(saveAction)
alertController.preferredAction = saveAction
self.present(alertController, animated: true, completion: nil)
}
Swift 4.0의 경우 프로젝트에서 성공적으로 테스트한 다음 코드 샘플을 사용할 수 있습니다.
@IBAction func withdrawTapped(_ sender: UIButton) {
let alertController = UIAlertController(title: "Token withdraw", message: "", preferredStyle: .alert)
let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { (aciton) in
let text = alertController.textFields!.first!.text!
if !text.isEmpty {
self.presentAlert(
title: "Succesful",
message: "You made request for withdraw \(textField.text) tokens")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
}
alertController.addTextField { (textField) in
textField.placeholder = "999"
textField.keyboardType = .decimalPad
}
alertController.addAction(withdrawAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
Swift 4.2 및 Xcode 10.1에서
두 개의 텍스트 필드와 읽기 텍스트 필드 텍스트 데이터로 경고하고 모든 보기 위에 경고를 표시합니다.
func alertWithTF(title: String, message: String) {
//Step : 1
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
//Step : 2
alert.addAction (UIAlertAction(title: "Save", style: .default) { (alertAction) in
let textField = alert.textFields![0]
let textField2 = alert.textFields![1]
if textField.text != "" {
//Read textfield data
print(textField.text!)
print("TF 1 : \(textField.text!)")
} else {
print("TF 1 is Empty...")
}
if textField2.text != "" {
//Read textfield data
print(textField2.text!)
print("TF 2 : \(textField2.text!)")
} else {
print("TF 2 is Empty...")
}
})
//Step : 3
//For first TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your first name"
textField.textColor = .red
}
//For second TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your last name"
textField.textColor = .blue
}
//Cancel action
alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
self.present(alert, animated:true, completion: nil)
}
모든 보기 위에 경고를 표시하려는 경우.
위의 코드에서 이 마지막 줄을 제거합니다.self.present(alert, animated:true, completion: nil)아래 코드를 추가합니다.
//Present alert on top of all views.
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated:true, completion: nil)
이제 이렇게 전화하세요.
alertWithTF(title: "This is title", message: "This is message")
텍스트 필드가 어떻게 사용될 수 있는지 보여주는 약간의 수정에 대한 답변입니다.
func addRow (row: Int, bodin: String, flag: Int) {
let alertController = UIAlertController(title: bodin, message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: {
alert -> Void in
_ = alertController.textFields![0] as UITextField
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
switch flag {
case 0:
textField.keyboardType = UIKeyboardType.phonePad
textField.placeholder = "Enter Number"
case 1:
textField.keyboardType = UIKeyboardType.emailAddress
textField.placeholder = "Enter Email"
default:
break
}
})
UIAlertController에 TextField 추가 및 Swift의 UI 레이블에 TextField 텍스트 표시
let alert = UIAlertController(title: "Alert", message: "", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "First Name"
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0]
self.label.text = textField?.text }))
self.present(alert, animated: true, completion: nil)
스위프트5
첫 번째 클래스가 UITextFieldDelegate를 준수한 다음 새 textField 속성을 만듭니다.
private var myTextField : UITextField?
// now where u want to add code
let alertContoller = UIAlertController.init(title: "Add", message: "My message to user", preferredStyle: .alert)
alertContoller.addTextField { (textField) in
// make sure your outside any property should be accessed with self here
self.myTextField = textField
//Important step assign textfield delegate to self
self.myTextField?.delegate = self
self.myTextField?.placeholder = self.textFieldPlaceholderText
}
let action = UIAlertAction.init(title: "Ok", style: .default) { action in
print("Alert tapped")
}
alertContoller.addAction(action)
present(alertContoller, animated: true, completion:nil)
감사해요.
private func showLoginAlert() {
let loginAlert = UIAlertController(title: "Login Using Credentials", message: nil, preferredStyle: .alert)
loginAlert.view.tintColor = .systemBlue
loginAlert.addTextField { usernameField in
usernameField.font = .systemFont(ofSize: 17.0)
usernameField.placeholder = "Username"
}
loginAlert.addTextField { passwordField in
passwordField.font = .systemFont(ofSize: 17.0)
passwordField.isSecureTextEntry = true
passwordField.placeholder = "Password"
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .destructive,
handler: { _ in
// self.handleUsernamePasswordCanceled(loginAlert: loginAlert)
})
loginAlert.addAction(cancelAction)
let loginAction = UIAlertAction(title: "Login",
style: .default,
handler: { _ in
// self.handleUsernamePasswordEntered(loginAlert: loginAlert)
})
loginAlert.addAction(loginAction)
loginAlert.preferredAction = loginAction
present(loginAlert, animated: true, completion: nil)
}
스위프트 5
언급URL : https://stackoverflow.com/questions/31922349/how-to-add-textfield-to-uialertcontroller-in-swift
'codememo' 카테고리의 다른 글
| PHP CLI는 사용자로부터 입력을 받은 다음 변수에 덤프하는 것이 가능합니까? (0) | 2023.08.16 |
|---|---|
| mysql/messagadbrict_trans_table 모드입니다.활성화하기 전에 로그 (0) | 2023.08.16 |
| Spring Framework를 사용하여 OPTIONS 요청에 대한 CORS 사용 (0) | 2023.08.16 |
| "SqlParameterCollection은 Null이 아닌 SqlParameter 유형 개체만 허용하고 String 개체는 허용하지 않습니다." (0) | 2023.08.16 |
| ORA-29283: "SYS"에서 잘못된 파일 작업 ORA-06512:.UTL_FILE", 536행 (0) | 2023.08.16 |