มี 2 วิธีหลักในการจำกัด UITextField ให้รับเฉพาะตัวเลข
วิธีที่ 1: ผ่าน Storyboard
- เลือก Text Field
- ไป Attribute Inspector
- Keyboard Type → เลือก Number Pad
วิธีที่ 2: เขียนโค้ด (UITextFieldDelegate)
- สร้าง outlet ของ Text Field
- Conform
UITextFieldDelegate - ตั้ง delegate ให้ text field
- ใช้เมธอด
textField(_:shouldChangeCharactersIn:replacementString:)
โค้ดตัวอย่าง
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tf: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tf.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let _ = string.rangeOfCharacter(from: .decimalDigits) {
return true
} else {
return false
}
}
}
วิธีนี้อนุญาตเฉพาะตัวเลข 0-9 ไม่อนุญาตให้พิมพ์อักษรหรือสัญลักษณ์อื่น