我正在使用UITextView
,我希望这样做,以便用户填写UITextView
后(您在故事板中进行填充,并且不允许用户输入这些尺寸在用户之外,用户不能再输入任何文本。基本上,现在发生的事情是即使看起来它已经填满了,我仍然打字就像一个你看不到的永无止境的文本框。我假设你在故事板中创建的尺寸是你看到文字的唯一空间。
有人可以帮助我吗?
答案 0 :(得分:3)
您可以使用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
}
}