如何在 Swift 中限制 UITextField 僅獲取數字?


在 iOS 應用中,有時我們需要將我們的文字欄位限制為僅接受數字作為輸入,這可以透過多種方式來實現,我們來看看其中一些。

方法 1:從情節提要中更改文字欄位型別。

  • 選擇你希望限制為數字輸入的文字欄位。
  • 轉到其屬性檢查器。
  • 選擇鍵盤型別並從那裡選擇數字鍵盤。

方法 2:透過程式設計方式將輸入限制為數字。

  • 選擇文字欄位
  • 在檢視控制器中建立它的出口。
  • 讓檢視控制器符合 UITextFieldDelegate
  • 設定文字欄位的委託
  • 新增以下函式
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
      return true
   } else {
      return false
   }
}

我們整個示例類的外觀如下

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
   @IBOutlet weak var tf: UITextField!
      override func viewDidLoad() {
         tf.delegate = self
         super.viewDidLoad()
      }
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
            return true
         } else {
         return false
      }
   }
}

這將建立一個只能以數字為輸入的文字欄位,不能輸入其他字元。

更新時間: 30-07-2019

6 千+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告