将用户的文本输入限制在 UITextView 的高度

Limiting user's text entry to the height of the UITextView

我正在使用 UITextView 并且我希望在用户填充 UITextView 后(您在情节提要中制作它,并且不允许用户使用这些尺寸在外面打字)用户不能再打字了。基本上,现在发生的情况是,即使它看起来已被填满,但我一直在输入它,就像一个你看不到的永无止境的文本框。我假设你在情节提要中制作的尺寸是你唯一看到文字的 space。

有人可以帮助我吗?

http://www.prntscr.com/671n1u

您可以使用UITextViewDelegate shouldChangeTextInRange:方法将文本输入限制在文本视图的高度:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    // Combine the new text with the old
    let combinedText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)

    // Create attributed version of the text
    let attributedText = NSMutableAttributedString(string: combinedText)
    attributedText.addAttribute(NSFontAttributeName, value: textView.font, range: NSMakeRange(0, attributedText.length))

    // Get the padding of the text container
    let padding = textView.textContainer.lineFragmentPadding

    // Create a bounding rect size by subtracting the padding
    // from both sides and allowing for unlimited length 
    let boundingSize = CGSizeMake(textView.frame.size.width - padding * 2, CGFloat.max)

    // Get the bounding rect of the attributed text in the
    // given frame
    let boundingRect = attributedText.boundingRectWithSize(boundingSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

    // Compare the boundingRect plus the top and bottom padding
    // to the text view height; if the new bounding height would be
    // less than or equal to the text view height, append the text
    if (boundingRect.size.height + padding * 2 <= textView.frame.size.height){
        return true
    }
    else {
        return false
    }
}