Bagaimana menambahkan TextField ke UIAlertController di Swift

96

Saya mencoba untuk menunjukkan UIAlertControllerdengan a UITextView. Ketika saya menambahkan baris:

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    }        

Saya mendapatkan Runtimekesalahan:

kesalahan fatal: tiba-tiba ditemukan nol saat membuka bungkus nilai Opsional

    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)

Ini disajikan di dalam my ViewControllervia an IBAction.

Saya telah mengunduh kode dari sini dan berfungsi dengan baik. Saya menyalin dan menempel metode itu ke dalam kode saya dan itu rusak. Kehadiran diri di baris terakhir tidak berdampak apa-apa.

Quintin Balsdon
sumber
UITextField, bukan UITextView?
benc

Jawaban:

194

Swift 5.1.0

alert.addTextField { (textField) in
    textField.placeholder = "Enter First Name"
}

Gunakan kode ini, saya berhasil menjalankan kode ini di aplikasi saya.

@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)
}

Diedit: Versi 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)
}
Himanshu Mahajan
sumber
23

Untuk menambahkan bidang teks di 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)
Meagan S.
sumber
11

Jadi saya mulai memeriksa untuk melihat apa yang mungkin berbeda dalam kode saya dengan kode yang berfungsi. Saya perhatikan bahwa ViewController saya meluas

UITextFieldDelegate

Yang tampaknya berarti saya perlu mengatur delegasi dari setiap anak UITextView:

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    searchTextField = textField
    searchTextField?.delegate = self //REQUIRED
    searchTextField?.placeholder = "Enter your search terms"
}
Quintin Balsdon
sumber
10

Larutan:

Swift 4.2.0

Coba baris berikut dan lihat apakah berhasil:

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)

Semoga membantu.

Ümañg ßürmån
sumber
Apakah urutan keduanya alertController.addTextFieldbenar? Sepertinya "Nama Kedua" akan muncul di atas "Nama Depan".
benc
6

Bagaimana cara menambahkan textField ke AlertView? Mari kita buat singkat dan sederhana.

Ini berfungsi untuk Swift 3.0 dan yang lebih baru.

var nameField: UITextField?
let alertController = UIAlertController(title: "Add Number", message: nil, preferredStyle: .alert)
// Add textfield to alert view
alertController.addTextField { (textField) in
    nameField = textField
}

Pertama, Anda membuat instance objek UIAlertControllerdan kemudian menambahkan bidang teks padanya dengan mengakses addTextFieldanggota UIAlertControllerkelas.

Maihan Nijat
sumber
4

Untuk menambahkan alertController dengan satu textField (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)
}
Hardik Thakkar
sumber
3

Untuk Swift 4.0, Anda dapat menggunakan contoh kode ini yang berhasil diuji dalam proyek saya:

@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)
}
5uper_0leh
sumber
3

Di Swift 4.2 dan Xcode 10.1

Peringatan dengan dua Textfields dan Baca data teks TextField dan sajikan peringatan di atas semua tampilan .

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)

}

Jika Anda ingin menyajikan aleert di atas semua tampilan.

Di sini dari kode di atas, hapus baris terakhir ini self.present(alert, animated:true, completion: nil)dan tambahkan kode di bawah ini.

//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)

Sekarang panggil seperti ini

alertWithTF(title: "This is title", message: "This is message")
iOS
sumber
1

Jawaban bagus, sedikit modifikasi untuk menunjukkan bagaimana textfield dapat digunakan:

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
        }

    })
Jeremy Andrews
sumber
1

tambahkan TextField ke UIAlertController dan TextField Text Display di UILabel di Swift

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)
ram
sumber
1

UIAlertControllerdengan UITextfielddi terbaru Apel Swift versi 5.1.3

Buat lazy variabel dari UIAlertControllerdalam Anda UIViewController, Tambah UITextFieldDelegate, Tampilkan Alert pada UIButtonAksi :

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
    }
}

Selamat Coding !! :)

Abimanyu Rathore
sumber
0

Swift5

Kelas pertama sesuai dengan UITextFieldDelegate, lalu buat properti textField baru

    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)

Terima kasih

dakrawat
sumber
0
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)
}

Cepat 5

Debaprio B
sumber