2017-08-01 56 views

回答

2

設置你的控制器爲代表的文本字段,並檢查提議的字符串滿足您的要求:

override func viewDidLoad() { 
    super.viewDidLoad() 
    textField.delegate = self 
    textField.keyboardType = .decimalPad 
} 

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    guard let oldText = textField.text, let r = Range(range, in: oldText) else { 
     return true 
    } 

    let newText = oldText.replacingCharacters(in: r, with: string) 
    let isNumeric = newText.isEmpty || (Double(newText) != nil) 
    let numberOfDots = newText.components(separatedBy: ".").count - 1 

    let numberOfDecimalDigits: Int 
    if let dotIndex = newText.index(of: ".") { 
     numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1 
    } else { 
     numberOfDecimalDigits = 0 
    } 

    return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2 
} 
+0

謝謝!它工作得很好。你能建議一些我可以學習的地方嗎?我正在使用大書呆子牧場的'ios編程'。它並沒有教它。 – KawaiKx

+1

沒有書可以涵蓋一切。那本Big Nerd Ranch書是一本介紹Swift和iOS編程的非常好的書。編程是不斷學習。你會發現從其他書籍或像StackOverflow網站丟失的部分:) –

+0

我如何允許減號輸入負面雙打? – KawaiKx

0

夥計們,這裏的解決方案:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     let dotString = "." 

     if let text = textField.text { 
      let isDeleteKey = string.isEmpty 

      if !isDeleteKey { 
       if text.contains(dotString) { 
        if text.components(separatedBy: dotString)[1].count == 2 { 

           return false 

        } 

       } 

      } 
     } 
    } 
相關問題