ios - UITextView 中的每个数字只允许一位小数(Swift 4)
问题描述
我有一个UITextView
输入一系列以空格分隔的数字(例如:“12.3 30 22.7 19.23 15 8.5 11”)。
可能包含多个小数点,UITextView
但我想确保没有单个数字包含多个小数位。
我发现的所有解决方案都只将整数限制UITextView
为一个小数,而不是每个数字。
我怎样才能做到这一点?
解决方案
你可以在 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
推荐阅读
- mysql - MySQL 根据一些匹配的字段和一些不匹配的字段查找重复项
- c# - 什么是最快的数据结构和/或算法在排序的数字列表或数组中找到插入位置而不实际插入(在 c# 中)
- java - 子阵列内的最佳最大差异
- c# - 我可以在 EF core asp.net 中使用相同的模型创建多个表吗
- java - 我如何优化下面的代码,以便它可以接受任何数组大小并给我结果
- php - Preg_match_all 与字边界和非字母数字字符
- java - Android Oreo 中手机连接充电器 (ACTION_POWER_CONNECTED) 时启动服务
- cockroachdb - 对 cockroachdb 的读/写有更好的解释吗?
- ruby-on-rails - Ajax 发布动态内容导轨 5.0.1
- java - Spring 集成消息历史记录