// // PBEditTextController.m // IphoneBIMe // // Created by zjf on 2018/8/14. // Copyright © 2018年 ProBIM. All rights reserved. // #import "PBEditTextController.h" #import "IQKeyboardManager.h" #define maxTextCount 150 @interface PBEditTextController () @property (nonatomic, weak) UITextView *textView; @property (nonatomic, weak) UILabel *textLengthL; @property (nonatomic, weak) UILabel *promptL; @end @implementation PBEditTextController - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[IQKeyboardManager sharedManager] setEnable:NO]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[IQKeyboardManager sharedManager] setEnable:YES]; } - (void)viewDidLoad { [super viewDidLoad]; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.f) { // self.edgesForExtendedLayout = UIRectEdgeNone; self.navigationController.interactivePopGestureRecognizer.enabled = YES; self.navigationController.interactivePopGestureRecognizer.delegate = self; } [self setupNav]; [self setupUI]; } //- (void)viewWillAppear:(BOOL)animated { // [super viewWillAppear:YES]; // //导航栏背景颜色 // [self.navigationController.navigationBar setBarTintColor:PBColor(35, 36, 41)]; // // 去掉导航条下边的线 // self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init]; // //返回按钮颜色 // self.navigationController.navigationBar.tintColor = [UIColor redColor]; // for (UIBarButtonItem *item in self.navigationItem.leftBarButtonItems) { // [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} forState:UIControlStateNormal]; // } // for (UIBarButtonItem *item in self.navigationItem.rightBarButtonItems) { // [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} forState:UIControlStateNormal]; // } //// [item setTitleTextAttributes:@{NSForegroundColorAttributeName: IndicatedColor} forState:UIControlStateHighlighted]; //// [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]} forState:UIControlStateDisabled]; // // //标题颜色 // [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName: [UIFont boldSystemFontOfSize:16]}]; //} - (void)setupNav { // PBBackNavItem *backNav = [PBBackNavItem backNacItem]; // backNav.title = @"取消"; // [backNav addTarget:self action:@selector(backItemAction) forControlEvents:UIControlEventTouchUpInside]; // UIBarButtonItem *backNavItem = [[UIBarButtonItem alloc] initWithCustomView:backNav]; UIBarButtonItem *backNavItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Doc_preview_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemAction)]; self.navigationItem.leftBarButtonItem = backNavItem; UIBarButtonItem *saveNavItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(saveText)]; self.navigationItem.rightBarButtonItem = saveNavItem; } - (void)backItemAction { [self.navigationController popViewControllerAnimated:YES]; } - (void)saveText { if(self.CompleteEditTextBlock) { self.CompleteEditTextBlock(_textView.text); } [self.navigationController popViewControllerAnimated:YES]; } - (void)setupUI { self.view.backgroundColor = [UIColor z_colorWithR:242 G:242 B:242]; UIView *bgView = [[UIView alloc] init]; bgView.backgroundColor = [UIColor whiteColor]; bgView.layer.borderWidth = 1.f; bgView.layer.borderColor = [[UIColor z_colorWithR:219 G:219 B:219] CGColor]; [self.view addSubview:bgView]; [bgView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view).offset(10); make.left.equalTo(self.view).offset(16); make.right.equalTo(self.view).offset(-16); make.height.equalTo(@250); }]; UITextView *textView = [[UITextView alloc] init]; textView.textColor= TitleColor; textView.font = [UIFont systemFontOfSize:TitleFontSize]; [textView becomeFirstResponder]; textView.delegate = self; textView.text = _text; [bgView addSubview:textView]; [textView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(bgView).offset(16); make.left.equalTo(bgView).offset(16); make.right.equalTo(bgView).offset(-16); make.bottom.equalTo(bgView).offset(-46); }]; UILabel *promptL= [UILabel z_labelWithText:_prompt Color:IgnoreColor isBold:NO Font:TitleFontSize]; [bgView addSubview:promptL]; [promptL mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(textView).offset(8); make.left.equalTo(textView).offset(6); }]; if (_text.length != 0) { promptL.hidden = YES; } UIButton *clearAllBtn = [UIButton z_bgImageButton:[UIImage imageNamed:@"Issue_editText_clearAll"]]; [clearAllBtn addTarget:self action:@selector(clearAllAction) forControlEvents:UIControlEventTouchUpInside]; [bgView addSubview:clearAllBtn]; [clearAllBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(bgView).offset(-11); make.left.equalTo(bgView).offset(22); make.size.mas_equalTo(CGSizeMake(79, 16)); }]; UILabel *textLengthL = [UILabel z_labelWithText:[NSString stringWithFormat:@"%lu/%d",(unsigned long)_text.length,maxTextCount] Color:DescColor isBold:NO Font:DescFontSize]; textLengthL.textAlignment = NSTextAlignmentRight; [bgView addSubview:textLengthL]; [textLengthL mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(clearAllBtn); make.right.equalTo(bgView).offset(-16); make.height.equalTo(@20); }]; self.textView = textView; self.promptL = promptL; self.textLengthL = textLengthL; } - (void)clearAllAction { _text = @""; _textView.text = _text; self.promptL.hidden = NO; _textLengthL.text = [NSString stringWithFormat:@"%lu/%d",(unsigned long)_text.length,maxTextCount]; } - (void)setText:(NSString *)text { _text = text; } - (void)setTitleText:(NSString *)titleText { self.title = titleText; } - (void)setPrompt:(NSString *)prompt { _prompt = prompt; } #pragma mark - UITextViewDelete - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { NSLog(@"%zd",textView.text.length); NSLog(@"===shouldChangeText"); UITextRange *selectedRange = [textView markedTextRange]; //获取高亮部分 UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0]; //获取高亮部分内容 //NSString * selectedtext = [textView textInRange:selectedRange]; //如果有高亮且当前字数开始位置小于最大限制时允许输入 if (selectedRange && pos) { NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start]; NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end]; NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset); if (offsetRange.location < maxTextCount) { return YES; } else{ return NO; } } NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text]; NSInteger caninputlen = maxTextCount - comcatstr.length; if (caninputlen >= 0){ return YES; }else{ NSInteger len = text.length + caninputlen; //防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错 NSRange rg = {0,MAX(len,0)}; if (rg.length > 0){ NSString *s = @""; //判断是否只普通的字符或asc码(对于中文和表情返回NO) BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding]; if (asc) { s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错 }else{ __block NSInteger idx = 0; __block NSString *trimString = @"";//截取出的字串 //使用字符串遍历,这个方法能准确知道每个emoji是占一个unicode还是两个 [text enumerateSubstringsInRange:NSMakeRange(0, [text length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) { if (idx >= rg.length) { *stop = YES; //取出所需要就break,提高效率 return ; } trimString = [trimString stringByAppendingString:substring]; idx++; }]; s = trimString; } //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件) [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]]; //既然是超出部分截取了,哪一定是最大限制了。 self.textLengthL.text = [NSString stringWithFormat:@"%d/%ld",0,(long)maxTextCount]; } return NO; } } - (void)textViewDidChange:(UITextView *)textView{ if (textView.text.length == 0) { self.promptL.hidden = NO; }else { self.promptL.hidden = YES; } NSLog(@"===DidChangeText"); UITextRange *selectedRange = [textView markedTextRange]; //获取高亮部分 UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0]; //如果在变化中是高亮部分在变,就不要计算字符了 if (selectedRange && pos) { return; } NSString *nsTextContent = textView.text; NSInteger existTextNum = nsTextContent.length; if (existTextNum > maxTextCount){ //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断) NSString *s = [nsTextContent substringToIndex:maxTextCount]; [textView setText:s]; } //不让显示负数 口口日 self.textLengthL.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,maxTextCount - existTextNum),maxTextCount]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end