fai*_*sal 24 iphone uitextview
我有一个UITextView,用户可以在textView中写入最多160个字符.如何修复UITextView的最大文本长度?
man*_*sar 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;
}
}
Run Code Online (Sandbox Code Playgroud)
Mad*_*dav 15
更换
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Run Code Online (Sandbox Code Playgroud)
同
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
Run Code Online (Sandbox Code Playgroud)
在这里回答
Hen*_*oke 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32553 次 |
| 最近记录: |