我有一个UITextView,用户可以在textView中写入最多160个字符。 如何修复UITextView的最大文本长度?
答案 0 :(得分:58)
这段代码也适用于复制/粘贴,但在尝试粘贴将使文本视图超出限制的字符数时也能应对这种情况。在这种情况下,只粘贴字符串的第一个字符。
#define MAX_LENGTH 15 // Whatever your limit is
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSUInteger newLength = (textView.text.length - range.length) + text.length;
if(newLength <= MAX_LENGTH)
{
return YES;
} else {
NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length);
textView.text = [[[textView.text substringToIndex:range.location]
stringByAppendingString:[text substringToIndex:emptySpace]]
stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]];
return NO;
}
}
答案 1 :(得分:15)
替换
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
与
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
已回答here
答案 2 :(得分:13)
迟到这个答案; manicaesar的解决方案对我不起作用。这是我对同一想法的实现:
#define MAX_LENGTH 140
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)replacementText
{
NSString *newText = [ textView.text stringByReplacingCharactersInRange: range withString: replacementText ];
if( [newText length]<= MAX_LENGTH ){
return YES;
}
// case where text length > MAX_LENGTH
textView.text = [ newText substringToIndex: MAX_LENGTH ];
return NO;
}
答案 3 :(得分:1)
Swift 4,
我在swift 4中编写了UITextView的扩展,以使代码可重用。复制粘贴也可以正常工作。
private var maxLengths = [UITextView: Int]()
extension UITextView : UITextViewDelegate {
@IBInspectable var maxLength: Int {
get {
guard let length = maxLengths[self]
else {
return Int.max
}
return length
}
set {
maxLengths[self] = newValue
self.delegate = self
}
}
@objc func limitLength(textView: UITextView) {
guard let prospectiveText = textView.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
text = String(prospectiveText[..<maxCharIndex])
selectedTextRange = selection
}
public func textViewDidChange(_ textView: UITextView) {
limitLength(textField:textView)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
scrollToBottom()
return true
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
scrollToBottom()
return true
}
func scrollToBottom() {
let location = text.count - 1
let bottom = NSMakeRange(location, 1)
self.scrollRangeToVisible(bottom)
}
}
在故事板中设置最大长度值
答案 4 :(得分:0)
Swift 3
fileprivate let maxLen = 5
extension MyViewController : UITextViewDelegate{
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let newLen = (textView.text.characters.count - range.length) + text.characters.count
return newLen <= maxLen
}
}