首页 > 解决方案 > UITextView 中的每个数字只允许一位小数(Swift 4)

问题描述

我有一个UITextView输入一系列以空格分隔的数字(例如:“12.3 30 22.7 19.23 15 8.5 11”)。

可能包含多个小数点,UITextView但我想确保没有单个数字包含多个小数位。

我发现的所有解决方案都只将整数限制UITextView为一个小数,而不是每个数字。

我怎样才能做到这一点?

标签: iosswift

解决方案


你可以在 UITextView 委托函数中尝试这样的事情shouldEndEditing

func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
    guard let numbers = textView.text else {
        return true
    }
    var hasMultipleDecimalPlaces: Bool = false
    let numbersAsList = numbers.split(separator: " ")
    for number in numbersAsList {
        let splitAtDecimal = number.split(separator: ".")
        if splitAtDecimal.count > 2 {
            if splitAtDecimal[1].count > 2 {
                // This is what you want to prevent so break early and return false
                hasMultipleDecimalPlaces = true
                break
            }
        }
    }
    return !hasMultipleDecimalPlaces

}

这将阻止用户完成对文本视图的编辑。它总是可以用在像这样的函数中shouldReplaceCharactersIn


推荐阅读