IOS UITextView支持输入、复制、粘贴、剪切自定义表情

时间:2023-03-10 00:48:28
IOS UITextView支持输入、复制、粘贴、剪切自定义表情

UITextView是ios的富文本编辑控件,除了文字还可以插入图片等。今天主要介绍一下UITextView对自定义表情的处理。

1、首先识别出文本中的表情文本,然后在对应的位置插入NSTextAttachment对象,该对象存放的就是自定义表情。

 static NSString *emojiTextPttern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]";

 _emojiDic = @{@"[大笑]":@"smile",@"[爱心]":@"love"};

 -(NSMutableAttributedString*)getEmojiText:(NSString*)content{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:content attributes:self.typingAttributes];
static NSRegularExpression *regExpress = nil;
if(regExpress == nil){
regExpress = [[NSRegularExpression alloc]initWithPattern:emojiTextPttern options: error:nil];
}
//通过正则表达式识别出emojiText
NSArray *matches = [regExpress matchesInString:content options: range:NSMakeRange(, content.length)];
if(matches.count > ){
for(NSTextCheckingResult *result in [matches reverseObjectEnumerator]){
NSString *emojiText = [content substringWithRange:result.range];
//构造NSTextAttachment对象
NSTextAttachment *attachment = [self createEmojiAttachment:emojiText];
if(attachment){
NSAttributedString *rep = [NSAttributedString attributedStringWithAttachment:attachment];
//在对应的位置替换
[attributedString replaceCharactersInRange:result.range withAttributedString:rep];
}
}
}
return attributedString;
}

2、构造NSTextAttachment的过程为:

 -(NSTextAttachment*)createEmojiAttachment:(NSString*)emojiText{
if(emojiText.length==){
return nil;
}
NSString *imageName = _emojiDic[emojiText];
if(imageName.length == ){
return nil;
}
UIImage *image = [UIImage imageNamed:imageName];
if(image == nil){
return nil;
}
//把图片缩放到符合当前textview行高的大小
CGFloat emojiWHScale = image.size.width/1.0/image.size.height;
CGSize emojiSize = CGSizeMake(self.font.lineHeight*emojiWHScale, self.font.lineHeight);
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(, , emojiSize.width, emojiSize.height)];
imageView.image = image;
//防止模糊
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *emojiImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
EmojiTextAttachment *attachment = [[EmojiTextAttachment alloc]init];
attachment.image = emojiImage;
attachment.emojiText = emojiText;
attachment.bounds = CGRectMake(, -, emojiImage.size.width, emojiImage.size.height);
return attachment;
}

其中EmojiTextAttachment继承了NSTextAttachment类,主要是为了记住自定义表情对应的emojiText,在后面实现copy和cut需要用到。EmojiTextAttachment声明为:

 @interface EmojiTextAttachment : NSTextAttachment

 /**
保存emojiText的值
*/
@property (nonatomic, strong) NSString *emojiText;
@end

3、实现对自定义表情的粘贴

重新paste方法即可

 -(void)paste:(id)sender{
UIPasteboard *defaultPasteboard = [UIPasteboard generalPasteboard];
if(defaultPasteboard.string.length>){
NSRange range = self.selectedRange;
if(range.location == NSNotFound){
range.location = self.text.length;
}
if([self.delegate textView:self shouldChangeTextInRange:range replacementText:defaultPasteboard.string]){
NSAttributedString *newAttriString = [self getEmojiText:defaultPasteboard.string];
[self insertAttriStringToTextview:newAttriString];
}
return;
}
[super paste:sender];
} -(void)insertAttriStringToTextview:(NSAttributedString*)attriString{
NSMutableAttributedString *mulAttriString = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
NSRange range = self.selectedRange;
if(range.location == NSNotFound){
range.location = self.text.length;
}
[mulAttriString insertAttributedString:attriString atIndex:range.location];
self.attributedText = [mulAttriString copy];
self.selectedRange = NSMakeRange(range.location+attriString.length, );
}

4、实现自定义表情的拷贝和剪切

拷贝和剪切自定义表情的时候,不是获取自定义表情对应的图片而是自定义表情对应的emojiText,这也是我们在上面要定义EmojiTextAttachment类的原因。具体代码如下:

 -(void)copy:(id)sender{
NSRange range = self.selectedRange;
NSString *content = [self getStrContentInRange:range];
if(content.length>){
UIPasteboard *defaultPasteboard = [UIPasteboard generalPasteboard];
[defaultPasteboard setString:content];
return;
}
[super copy:sender];
}
-(void)cut:(id)sender{
NSRange range = self.selectedRange;
NSString *content = [self getStrContentInRange:range];
if(content.length>){
[super cut:sender];
UIPasteboard *defaultPasteboard = [UIPasteboard generalPasteboard];
[defaultPasteboard setString:content];
return;
}
[super cut:sender];
} /**
把textview的attributedText转化为NSString,其中把自定义表情转化为emojiText @param range 转化的范围
@return 返回转化后的字符串
*/
-(NSString*)getStrContentInRange:(NSRange)range{
NSMutableString *result = [[NSMutableString alloc]initWithCapacity:];
NSRange effectiveRange = NSMakeRange(range.location,);
NSUInteger length = NSMaxRange(range);
while (NSMaxRange(effectiveRange)<length) {
NSTextAttachment *attachment = [self.attributedText attribute:NSAttachmentAttributeName atIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];
if(attachment){
if([attachment isKindOfClass:[EmojiTextAttachment class]]){
EmojiTextAttachment *emojiAttachment = (EmojiTextAttachment*)attachment;
[result appendString:emojiAttachment.emojiText];
}
}
else{
NSString *subStr = [self.text substringWithRange:effectiveRange];
[result appendString:subStr];
}
}
return [result copy];
}

通过上面的努力,我们已经实现了所有的功能。但是我们用起来的时候,会发现两个问题:

1、在自定义表情的后面输入文本,UITextview设置的属性(比如字体大小,颜色等)都消失,又变成了默认属性;

2、在ios 10.11系统上,长按自定义表情的时候,keyboard会退出,并且弹出保存图片的系统窗口,这样的体验也不好。

解决第一个问题:

我们在初始化的时候保存一下UITextview的typingAttributes属性,然后在每次UITextview的内容将要发生变化的时候,重置一下他的该属性。

 @interface ViewController ()<UITextViewDelegate>
@property (nonatomic, strong)CustomTextView *textView; @property (nonatomic, strong)NSDictionary *typingAttributes;
@end -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
textView.typingAttributes = self.typingAttributes;
return YES;
}

解决第二个问题:

只需要实现一个delegate方法就行,直接返回NO

 -(BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
return NO;
}