我启用了滚动UITextView
,我可以更改内部文字的字体和大小。那么,我该如何设置文本限制?我已经尝试设置最大行数和最大字符数,但它不起作用,因为我需要设置文本的大小限制,我该怎么做?
答案 0 :(得分:10)
您必须实施UITextViewDelegate
:
class ViewController: UIViewController, UITextViewDelegate {
然后在viewDidLoad-method中设置textView的委托:
yourTextView.delegate = self
之后,您可以使用shouldChangeTextInRange
方法检查字母:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let maxtext: Int = 140
//If the text is larger than the maxtext, the return is false
// Swift 2.0
return textView.text.characters.count + (text.characters.count - range.length) <= maxtext
// Swift 1.1
// return countElements(textView.text) + (countElements(text.length) - range.length) <= maxtext
}
此解决方案的优点在于,您甚至可以控制剪切/复制和粘贴。因此,用户无法通过复制欺骗该字段接受更多字母。
答案 1 :(得分:4)
1)class ViewController: UIViewController, UITextViewDelegate {
2)textView.delegate = self
3)
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let maxCharacter: Int = 1000
return (textView.text?.utf16.count ?? 0) + text.utf16.count - range.length <= maxCharacter
}
答案 2 :(得分:2)
通常您必须符合UITextFieldDelegate
协议,将视图控制器指定为delegate
的{{1}}(在IB或代码中指定此参数),然后实现{ {1}}考虑字符串的长度:
UITextField
另一方面,如果您想控制输入的文本数量以符合控件的大小,您可以使用前面提到的shouldChangeCharactersInRange
,但使用func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldString = textField.text ?? ""
let startIndex = oldString.startIndex.advancedBy(range.location)
let endIndex = startIndex.advancedBy(range.length)
let newString = oldString.stringByReplacingCharactersInRange(startIndex ..< endIndex, withString: string)
return newString.characters.count <= kMaxLength
}
来指示是否method返回true或false而不是字符数。
这不太对,但它说明了基本的想法:
shouldChangeTextInRange