我正在尝试在两个textFields上添加字符限制限制。我也将十进制输入限制为只有一个十进制,似乎工作正常。我的角色限制导致许多错误。这是最好的方法吗?
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
let characterLimit = 8
let countdotsStockPrice = (stockPrice.text?.components(separatedBy: ".").count)! - 1
let countdotsCapitalInvested = (capitalInvested.text?.components(separatedBy: ".").count)! - 1
//TextField1: stockPrice.text
let currentString: NSString = (stockPrice.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
//TextField2: capitalInvested.text
let currentStringCapital: NSString = (capitalInvested.text ?? "") as NSString
let newStringCapital = currentStringCapital.replacingCharacters(in: range, with: string)
if textField == stockPrice {
if (newString.characters.count >= characterLimit) {
stockPrice.deleteBackward()
}
if countdotsStockPrice > 0 && string == "." { return false} else {return true}
} else if textField == capitalInvested {
if (newStringCapital.characters.count >= characterLimit) {
capitalInvested.deleteBackward()
}
if countdotsCapitalInvested > 0 && string == "." { return false} else {return true}
}
if textField == stockPrice || textField == capitalInvested {
}
return true
}
答案 0 :(得分:1)
检查一下,
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// check decimal restriction
let replacementStringIsLegal = string.rangeOfCharacter(from: CharacterSet(charactersIn:"0123456789")) == nil
if !replacementStringIsLegal {
return false
}
let nsString = textField.text as NSString?
let newString = nsString!.replacingCharacters(in: range, with: string)
// check maximum length
if newString.characters.count > 4 {
return false
}
return true
}
希望这会对你有所帮助。
答案 1 :(得分:0)
您可以这样存档:
private let decimalSeparator = "."
func isFractionalPartValid(in string: String) -> Bool {
let maxFractionalPartLength = 1
guard let separator = decimalSeparator.characters.first,
let comaIndex = string.characters.index(of: separator),
string.distance(from: comaIndex, to: string.endIndex) > maxFractionalPartLength + 1 else {
return true
}
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let set = CharacterSet.decimalDigits.union(CharacterSet(charactersIn: decimalSeparator)).inverted
let maxLength = 8
let currentString: NSString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
if newString.characters.count > maxLength || newString.rangeOfCharacter(from: set) != nil {
return false
}
//Below is not required but possibly you need it ;)
if newString.characters.count == maxLength && newString.characters.last == decimalSeparator.characters.first {
return false
}
return isFractionalPartValid(in: newString)
}
但老实说,我认为你应该把这个逻辑转移到另一个对象