UITextView 长度问题

UITextView length issue

我有一个启用了滚动功能的 UITextView,我可以更改其中文本的字体和大小。那么,如何设置文本限制?我已经尝试设置最大行数和最大字符数,但它不起作用,因为我需要设置文本的大小限制,我该怎么做?

您必须实施 UITextViewDelegate:

class ViewController: UIViewController, UITextViewDelegate {

然后在viewDidLoad方法中设置textView的delegate:

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 

}

此解决方案的优点在于,您甚至可以控制 cut/copy 和粘贴。所以用户不能通过复制来欺骗字段接受更多的字母。

通常你会遵守 UITextFieldDelegate 协议,将你的视图控制器指定为 UITextFielddelegate(在 IB 或代码中指定)然后实现考虑字符串长度的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
}

另一方面,如果您想控制输入的文本量以符合控件的大小,您可以使用前面提到的 shouldChangeTextInRange,但使用 sizeWithAttributes 来指定该方法 returns 是真还是假而不是字符数。

这不太正确,但它说明了基本思想:

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)
    let stringSize = newString.sizeWithAttributes([NSFontAttributeName : textField.font ?? UIFont.systemFontSize()])

    return stringSize.width < textField.editingRectForBounds(textField.bounds).size.width
}

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        
    }