如何在swift 4中将文本字段输入限制为2位小数? [英] How to limit the textfield entry to 2 decimal places in swift 4?

查看:499
本文介绍了如何在swift 4中将文本字段输入限制为2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,我想将条目限制为最多2位小数。

I have a textfield and I want to limit the entry to max 2 decimal places.

允许12.34之类的号码,但不允许12.345

number like 12.34 is allowed but not 12.345

我该怎么做?

推荐答案

将控制器设置为文本字段的委托,并检查建议的字符串是否满足您的要求:

Set your controller as the delegate for the text field and check if the proposed string satisfy your requirements:

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
}

这篇关于如何在swift 4中将文本字段输入限制为2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆