ios怎么限制uitextview输入文字的长度
1个回答
展开全部
这个只需要在UItextview的代理函数里面写限制即可,说白了就是判断当前字符串长度大于了你的限制字数,就把后面的删除掉就可以了
范例代码 范例代码仅仅是Controller的m文件
#import "ViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (strong ,nonatomic) UITextView *text;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.text = [[UITextView alloc]initWithFrame:CGRectMake(0, 20, 300, 300)];
[self.view addSubview:self.text];
[self.text setBackgroundColor:[UIColor grayColor]];
self.text.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
#define MY_MAX 20
if ((textView.text.length - range.length + text.length) > MY_MAX)
{
NSString *substring = [text substringToIndex:MY_MAX - (textView.text.length - range.length)];
NSMutableString *lastString = [textView.text mutableCopy];
[lastString replaceCharactersInRange:range withString:substring];
textView.text = [lastString copy];
return NO;
}
else
{
return YES;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
范例代码 范例代码仅仅是Controller的m文件
#import "ViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (strong ,nonatomic) UITextView *text;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.text = [[UITextView alloc]initWithFrame:CGRectMake(0, 20, 300, 300)];
[self.view addSubview:self.text];
[self.text setBackgroundColor:[UIColor grayColor]];
self.text.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
#define MY_MAX 20
if ((textView.text.length - range.length + text.length) > MY_MAX)
{
NSString *substring = [text substringToIndex:MY_MAX - (textView.text.length - range.length)];
NSMutableString *lastString = [textView.text mutableCopy];
[lastString replaceCharactersInRange:range withString:substring];
textView.text = [lastString copy];
return NO;
}
else
{
return YES;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询