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

        } 

       } 

      } 
     } 
    } 
相关问题