การเช็ค UITextField ว่างหรือไม่ว่างใน Swift
วิธีมาตรฐานและปลอดภัยที่สุดคือใช้ Optional Binding ร่วมกับ property isEmpty
โค้ดแป้งเดียว (Best Practice)
if let text = myTextField.text, !text.isEmpty {
// Text field มีข้อมูล (ไม่ว่าง)
} else {
// Text field ว่าง หรือเป็น nil
}
ตัวอย่างโปรเจกต์ครบถ้วน
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → Single View App → ชื่อ "CheckEmptyTextField"
ขั้นตอนที่ 2: ออกแบบ UI ใน Storyboard
- UITextField (สำหรับกรอกข้อความ)
- UIButton ตั้งชื่อ "Check"
- UILabel สำหรับแสดงผลลัพธ์
ขั้นตอนที่ 3: สร้าง IBOutlet และ IBAction
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func checkTextField(_ sender: Any) {
if let text = textField.text, !text.isEmpty {
resultLabel.text = "Text Field is not empty"
resultLabel.textColor = .systemGreen
} else {
resultLabel.text = "Text field is empty"
resultLabel.textColor = .systemRed
}
}
ขั้นตอนที่ 4: รันทดสอบ
- รันแอป → กด Check โดยไม่พิมพ์ → แสดง "Text field is empty"
- พิมพ์ข้อความ → กด Check → แสดง "Text Field is not empty"
เคล็ดลับเพิ่มเติม
- Trim whitespace: ใช้
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmptyหากไม่นับ Space/Enter - Validation แบบ Real-time: ใช้
UITextFieldDelegateหรือ Combine framework - Placeholder: ตั้ง
placeholderให้ผู้ใช้ทราบว่าควรกรอกอะไร