我有一个UITextView,其中字符条目限制为100个数字。当文本通过键盘输入到文本视图时,我能够使用textView:shouldChangeTextInRange:replacementText:方法跟踪字符条目。在我的情况下,也有可能用户只是输入字符文本视图的按钮点击,没有任何中断的键盘。在这种情况下,上面的委托方法没有被调用,所以我不能跟踪文本视图中的字符数,从而允许超过100个字符。如何处理这种情况?请帮助。
你可以试试下面的Swift 3代码:-
@IBAction func buttonClicked(sender: AnyObject) {
self.textView.text = self.textView.text + "AA" //suppose you are trying to append "AA" on button click which would call the below delegate automatically
}
//Below delegate of UITextViewDelegate will be called from keyboard as well as in button click
func textViewDidChangeSelection(_ textView: UITextView) {
if textView.text.characters.count > 100 {
let tempStr = textView.text
let index = tempStr?.index((tempStr?.endIndex)!, offsetBy: 100 - (tempStr?.characters.count)!)
textView.text = tempStr?.substring(to: index!)
}
}
据我所知,你有自定义按钮附加一些文本到textField的现有文本,对吗?
在这种情况下,你可以实现一个验证方法
func validateString(string: String) -> Bool {
return string.characters.count <= 100
}
并在shouldChangeCharactersInRange
方法和按钮回调中使用:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let currentString: NSString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return validateString(string: newString)
}
@IBAction func buttonPressed() {
let newString = textField.text + "a" //replace this line with your updated string
if validateString(string: newString) {
textField.text = newString
}
}