我有一个UITextView,其中字符输入限制为100个数字。当文本通过键盘输入到文本视图时,我能够使用textView:shouldChangeTextInRange:replacementText:方法跟踪字符条目。 在我的情况下,用户只需在按钮点击时将字符输入文本视图,而不会中断键盘。在这种情况下,上面的委托方法不会被调用,因此我无法跟踪文本视图中的字符数,从而允许超过100个字符。 应如何处理此类案件?请帮忙。
答案 0 :(得分:1)
您可以尝试以下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!)
}
}
答案 1 :(得分:0)
据我了解,你有自定义按钮可以将一些文本附加到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
}
}