24

iOSTextFiled,TextView过滤表情,限制长度

 5 years ago
source link: https://xiaodongxie1024.github.io/2019/03/21/20190321_iOS_textContentFilter/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

需求:在文本框中限制输入表情,长度限制

实现原理: 通过这两个控件的代理与通知实现

阅读前提:

  • 由于搜狗等不断改善,可能小部分表情未能限制
  • 原理较为简单,不再讲解

GitHub地址(附代码) :

简书地址 :

博客地址 :

掘金地址 :

注意

  1. 可以根据需求自行更改提示样式等等
  2. 可以根据需求自行优化过滤算法
  3. 好处:我们只需要有这样一个类,以后项目中所有需要限制的地方仅仅需要直接导入头文件,引用类方法即可

使用方法:

1. 导入头文件

#import "XDXTextContentHandler.h"

2. 直接在对应的代理或通知中对用头文件即可

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.testTextFiled.delegate = self;
    self.testTextView.delegate  = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextFieldTextDidChangeNotification"
                                               object:self.testTextFiled];
}


#pragma mark - Notification
- (void)textFiledEditChanged:(NSNotification *)obj {
    [XDXTextContentHandler handleTextFiledEditChangedWithNotification:obj textMaxLength:kTitleTextMaxLength isShowTip:YES];
}
#pragma mark - Delegate

#pragma mark TextFiled
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [XDXTextContentHandler handleTextFiledShouldChangeTextInRangeWithTextFiled:textField range:range replacementText:string isShowTip:YES];
}

#pragma mark TextView
- (void)textViewDidChange:(UITextView *)textView {
    [XDXTextContentHandler handleTextViewDidChangeWithTextView:textView textMaxLength:kTitleTextMaxLength isShowTip:YES];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return [XDXTextContentHandler handleTextViewShouldChangeTextInRangeWithTextView:textView range:range replacementText:text isShowTip:YES];
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK