一、属性
//自定义的textview
@property (weak, nonatomic) IBOutlet UITextView *textview;
//添加一个bool类型的属性
@property (nonatomic, assign) BOOL isNameTextFieldEnbable;
二、监听通知、并初始化BOOL值
//UITextView的监听方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textchange:) name:UITextViewTextDidChangeNotification object:nil];
//初始化为YES,让textView开始输入有反应
self.isNameTextFieldEnbable = YES;
三、监听方法
/** 监听方法 */
-(void)textchange:(NSNotification *)note{
//最大字数
static const NSInteger Max_Num_TextView = 5;
//监听开始默认YES
self.isNameTextFieldEnbable = YES;
//当前输入语言状态
UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
NSString *lang = mode.primaryLanguage;
//汉字
if ([lang isEqualToString:@"zh-Hans"]) {
UITextRange *selectedRange = [self.textview markedTextRange];
//高亮状态的start位置
UITextPosition *position = [self.textview positionFromPosition:selectedRange.start offset:0];
//没有高亮状态,即每次截取要在文字确认之后
if (!position) {
if (self.textview.text.length > Max_Num_TextView) {
self.textview.text = [self.textview.text substringToIndex:Max_Num_TextView];
self.isNameTextFieldEnbable = NO;
}
}
}
//非汉字状态
else{
if (self.textview.text.length > Max_Num_TextView) {
self.textview.text = [self.textview.text substringToIndex:Max_Num_TextView];
self.isNameTextFieldEnbable = NO;
}
}
}
四、TextView的代理方法
//是否允许键盘输入
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//返回删除键
if ([text isEqualToString:@""]) {
return YES;
}else{
return _isNameTextFieldEnbable;
}
}