Nsdatadetector is a subclass of nsregularexpression, primarily used to detect semi-structured data: dates, addresses, phone numbers, regular expressions, and so on.
First there is a string
NSString *str = @ "www.baidu.comdhfjdfj17701031767";
Initialized based on the type of detection here is the detection phone number and URL
Nsdatadetector nsdatadetector *detector = [Nsdatadetector datadetectorwithtypes:nstextcheckingtypephonenumber | Nstextcheckingtypelink error:&error];
Getting an array of detections
Nsarray *matches = [detector matchesinstring:str options:0 Range:inputrange];
Total number of detections obtained
-(Nsuinteger) numberofmatchesinstring: (NSString *) string options: (nsmatchingoptions) options range: (nsrange) Range ;
The first detected data
-(Nstextcheckingresult *) firstmatchinstring: (NSString *) string options: (nsmatchingoptions) options range: (Nsrange ) range;
For (Nstextcheckingresult *match in matches) {
Set color when match matches to URL
if ([match resulttype] = = Nstextcheckingtypelink) {
Nsrange Matchrange = [Match range];
if ([self isindex:index inrange:matchrange]) {
[Attributedstring addattribute:nsforegroundcolorattributename Value:[uicolor Graycolor] range:matchRange];
}
else {
[Attributedstring addattribute:nsforegroundcolorattributename Value:[uicolor Bluecolor] range:matchRange];
}
[Attributedstring addattribute:nsunderlinestyleattributename value:[nsnumber Numberwithinteger: Nsunderlinestylesingle] Range:matchrange];
}
Set its attribute when match matches a phone number
if ([match resulttype] = = Nstextcheckingtypephonenumber) {
Nsrange Matchrange = [Match range];
if ([self isindex:index inrange:matchrange]) {
[Attributedstring addattribute:nsforegroundcolorattributename Value:[uicolor Graycolor] range:matchRange];
}
else {
[Attributedstring addattribute:nsforegroundcolorattributename Value:[uicolor Yellowcolor] range:matchRange];
}
[Attributedstring addattribute:nsunderlinestyleattributename value:[nsnumber Numberwithinteger: Nsunderlinestylesingle] Range:matchrange];
}
_textlabel.attributedtext = attributedstring;
}
-(BOOL) Isindex: (cfindex) Index InRange: (nsrange) Range
{
return index > Range.location && Index < range.location+range.length;
}
Nstextcheckingresult class iOS comes with identification phone number, URL, etc.