你還在爲不會寫正則而抓狂?
html
電話號碼
、
連接
、
日期
、
地址
...並實現國際化而煩惱?
class
,
NSDataDetector
只是知道這個類的人甚少。
NSDataDetector
它是繼承至
NSRegularExpression
的,也就是咱們所說的正則表達式。
NSDataDetector
的使用很簡單,有一個類方法和一個實例方法。
+ (nullable NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error;
- (nullable instancetype)initWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error NS_DESIGNATED_INITIALIZER;複製代碼
這裏的type
就是咱們須要匹配的類型。這些 type 都是系統幫咱們定義好的,固然咱們也能夠本身自定義type
。git
typedef NS_OPTIONS(uint64_t, NSTextCheckingType) { // a single type
NSTextCheckingTypeOrthography = 1ULL << 0, // language identification
NSTextCheckingTypeSpelling = 1ULL << 1, // spell checking
NSTextCheckingTypeGrammar = 1ULL << 2, // grammar checking
NSTextCheckingTypeDate = 1ULL << 3, // date/time detection
NSTextCheckingTypeAddress = 1ULL << 4, // address detection
NSTextCheckingTypeLink = 1ULL << 5, // link detection
NSTextCheckingTypeQuote = 1ULL << 6, // smart quotes
NSTextCheckingTypeDash = 1ULL << 7, // smart dashes
NSTextCheckingTypeReplacement = 1ULL << 8, // fixed replacements, such as copyright symbol for (c)
NSTextCheckingTypeCorrection = 1ULL << 9, // autocorrection
NSTextCheckingTypeRegularExpression NS_ENUM_AVAILABLE(10_7, 4_0) = 1ULL << 10, // regular expression matches
NSTextCheckingTypePhoneNumber NS_ENUM_AVAILABLE(10_7, 4_0) = 1ULL << 11, // phone number detection
NSTextCheckingTypeTransitInformation NS_ENUM_AVAILABLE(10_7, 4_0) = 1ULL << 12 // transit (e.g. flight) info detection
};複製代碼
這僅僅是第一步,這一步就比如咱們寫好了正則表達式,那麼下一步就是將它運用在字符串中進行匹配。這裏有5種方法可共選擇github
//1.檢測而後對每一個檢測到的數據進行操做
- (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (^)(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop))block;
//2.檢測得到檢測獲得的數組
- (NSArray *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//3.得到檢測獲得的總數
- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//4.第一個檢測到的數據
- (NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//5.第一檢測到的數據的Range
- (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;複製代碼
匹配到了對應的字符串並知道了字符串對應所在的NSRange
,接下來就能夠利用NSMutableAttributedString
來讓這些字符串高亮。正則表達式
UITextView
中能夠直接響應高亮文本的事件,先設置 UITextView 的delegate
,並實現- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
協議。此時要設置 UITextView 的editable
爲NO
,否則不會走回調的API
。- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
方法設置響應事件,name
爲NSLinkAttributeName
,value
爲響應事件接收到的 value,range
爲須要響應事件的 range。其實在 Label 中實現文本高亮並實現事件的響應,在 Github 上面有不少庫了,例如YYText中的 YYLabel、TTTAttributedLabel等等,太多了就不一一列舉了,可是在YYLabel
中同時實現長按事件和點擊事件的時候,響應長按事件以後還會響應點擊事件,這時候就須要咱們本身手動處理一下了。express
參考文章:初識 NSDataDetector 數組