2017-08-01 19 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

Guysは、ここでの解決策です:

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 

        } 

       } 

      } 
     } 
    } 
関連する問題