Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

จำกัด UITextField ให้รับเฉพาะตัวเลขใน Swift

มี 2 วิธีหลักในการจำกัด UITextField ให้รับเฉพาะตัวเลข

วิธีที่ 1: ผ่าน Storyboard

  1. เลือก Text Field
  2. ไป Attribute Inspector
  3. Keyboard Type → เลือก Number Pad

วิธีที่ 2: เขียนโค้ด (UITextFieldDelegate)

  1. สร้าง outlet ของ Text Field
  2. Conform UITextFieldDelegate
  3. ตั้ง delegate ให้ text field
  4. ใช้เมธอด 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 ไม่อนุญาตให้พิมพ์อักษรหรือสัญลักษณ์อื่น