จากในรูป กรณีนี้ alert เด้งขึ้นมามี textField และ datetime Picker กรณีที่ต้องการให้ค่า picker ที่เราเลือกใส่เข้าไปใน textField ใน alert controller โดยปกติเวลาจะใส่ค่าให้ textField จะใช้วิธีการกำหนดค่าได้เลยลักษณะนี้นะครับ
1 2 |
let mytext = UITextView(...) mytext.text = "ใ่ส่ข้อความที่นี่" |
จากโค้ดด้านบน กำหนด textView ขึ้นมาและใส่ค่า โดยอ้างถึง textView โดยตรงได้เลย แต่ใน textField ใน alert controller ต้องทำผ่าน alert controller เท่านั้น จากโค้ดด้านล่าง เป็นการสร้าง alert controller พร้อม textField
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//1. Create the alert controller. let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert) //2. Add the text field. You can configure it however you need. alert.addTextField { (textField) in textField.text = "Some default text" } // 3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert.textFields![0] // Force unwrapping because we know it exists. print("Text field: \(textField.text)") })) // 4. Present the alert. self.present(alert, animated: true, completion: nil) |
เราจะอ้างถึง textField ใน alert controller ดังนี้
1 |
let myInput = alert.textFields![0] |
โดย 0 หมายถึง field ที่สร้างเรียงตามลำดับครับ
0