zjf
2023-03-06 392b76515f40376b6d36f40a114850ef63650384
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//
//  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 ()<UITextViewDelegate, UIGestureRecognizerDelegate>
@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