[英]Limit length of several text fields
I have several text fields in one view controller and I'm using the following function to limit the number of characters: 我在一个视图控制器中有几个文本字段,并且正在使用以下函数来限制字符数:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= 300
}
How can I change the number of maximum number of characters for a different text field? 如何更改不同文本字段的最大字符数? I need a lower limit for another text field.
我需要另一个文本字段的下限。
For TextView you need to use following TextView delegate method 对于TextView,您需要使用以下TextView委托方法
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
if textView == yourTextViewName
{
let str = (NSString(string: textView.text!)).replacingCharacters(in: range, with: text)
if str.characters.count <= 300 {
return true
}
textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
return false
}
return true
}
For TextField you have to use following delegate method 对于TextField,您必须使用以下委托方法
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if textField == yourTextFieldName {
let str = (NSString(string: textField.text!)).replacingCharacters(in: range, with: string)
if str.characters.count <= 300 {
return true
}
textField.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
return false
}
return true
}
I hope this help you. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.