您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 限制輸入表情符號:用正則表達式即時過濾

編輯:iOS 相關教學

有些後端或資料格式無法處理 Emoji,使用者貼上來就會變成亂碼甚至造成儲存失敗。解法是在輸入階段攔下來,用正則表達式把不在允許範圍內的字元移除。

一、效果預覽

二、專案結構

三、程式碼

RootViewController.h

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController <UITextViewDelegate>
@end

RootViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // 建立介面
    [self addView];
}

#pragma mark - 介面
-(void)addView {
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 200, 50)];
    textView.backgroundColor = [UIColor redColor];
    textView.delegate = self;
    [self.view addSubview:textView];
}

#pragma mark - UITextViewDelegate
// 內容每次變動都重新過濾一次
- (void)textViewDidChange:(UITextView *)textView {
    NSRange textRange = [textView selectedRange];
    [textView setText:[self disable_emoji:[textView text]]];
    [textView setSelectedRange:textRange];
}

// 過濾表情符號
- (NSString *)disable_emoji:(NSString *)text {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
        @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"
        options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
        options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];
    return modifiedString;
}

幾個實作細節

  • 正則的開頭 [^...] 是「排除清單」,也就是清單外的字元才會被移除;清單內涵蓋常用英文標點、中日韓字元與全形符號。
  • 過濾後一定要還原 selectedRange,否則游標會跳到最前面,輸入體驗很差。
  • 如果欄位是 UITextField,改在 shouldChangeCharactersInRange:replacementText: 中處理更合適,可以直接回傳 NO 阻擋輸入。
  • 這類過濾會讓使用者輸入的內容無聲消失,建議搭配提示文字說明限制,避免困惑。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved