我有a[i][k] >= m.m * sum (j in N) G[i][j][k][m];
,并且我希望允许用户最多键入4个符号。但是我也想允许他们用键盘擦除符号(我的意思是删除最后一个并向左移动插入符号。符号看起来像是iOS键盘上带有十字的矩形左箭头)。
现在我最终得到了:
UITextField
但是我不知道如何让用户删除符号。当文字计数变为4时,我将不允许键入或执行任何操作。
答案 0 :(得分:0)
使用此
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textField.text!.count + string.count < 5
}
答案 1 :(得分:0)
来自textField(_:shouldChangeCharactersIn:replacementString:)
当用户删除一个或多个字符时,替换字符串为空。
因此,您所缺少的只是检查替换字符串是否为空:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || (textField.text?.count ?? 0) < 4
}
答案 2 :(得分:0)
您必须在range方法中检查应更改字符的长度。就像关注
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = textField.text.length + (string.length - range.length)
if newLength <= maxLength {
return true
} else {
return false
}
}
maxLength是您要允许的字符的最大长度
答案 3 :(得分:0)
您可以使用下面的代码获取更新的字符串,并将其与您的长度进行比较,
func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// limit to 4 characters
let characterCountLimit = 4
// We need to figure out how many characters would be in the string after the change happens
let startingLength = textFieldToChange.text?.count ?? 0
let lengthToAdd = string.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
return newLength <= characterCountLimit
}