iOS使用UIDataDetectorType简单验证手机号、邮箱、网址

1,985 阅读2分钟

欢迎大家关注我的公众号,我会定期分享一些我在项目中遇到问题的解决办法和一些iOS实用的技巧,现阶段主要是整理出一些基础的知识记录下来

文章也会同步更新到我的博客:
ppsheep.com

这里只是做简单的手机号、邮箱和网址的验证,如果需要复杂的,请使用正则验证,或者其他强大的验证方式。

UIKit框架 有一个自带的验证手机号 邮箱等 的一个类 UIDataDetector.h

有时候 我们在项目里 并不需要那么复杂的验证 可能只是想要有手机号时 能够点击拨打电话这么简单,那么我们就没有必要去做复杂的正则验证了,用UIDataDetectorTypes就已经足够了

看一下UIDataDetectorTypes中的类型

typedef NS_OPTIONS(NSUInteger, UIDataDetectorTypes) {
    UIDataDetectorTypePhoneNumber                                        = 1 << 0, // Phone number detection
    UIDataDetectorTypeLink                                               = 1 << 1, // URL detection
    UIDataDetectorTypeAddress NS_ENUM_AVAILABLE_IOS(4_0)                 = 1 << 2, // Street address detection
    UIDataDetectorTypeCalendarEvent NS_ENUM_AVAILABLE_IOS(4_0)           = 1 << 3, // Event detection
    UIDataDetectorTypeShipmentTrackingNumber NS_ENUM_AVAILABLE_IOS(10_0) = 1 << 4, // Shipment tracking number detection
    UIDataDetectorTypeFlightNumber NS_ENUM_AVAILABLE_IOS(10_0)           = 1 << 5, // Flight number detection
    UIDataDetectorTypeLookupSuggestion NS_ENUM_AVAILABLE_IOS(10_0)       = 1 << 6, // Information users may want to look up

    UIDataDetectorTypeNone          = 0,               // Disable detection
    UIDataDetectorTypeAll           = NSUIntegerMax    // Enable all types, including types that may be added later
} __TVOS_PROHIBITED;

这里有这么多种类 当然我们不是全都用得上

包含了电话号 链接 还有地址 日期事件 航班号等等 当然 有的是 要到10.0才能用得上

使用起来 也很方便的

UITextView中有一个属性 是dataDetectorTypes 直接指定类型 就可以直接判断得出

UITextView *textView1 = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width, 200)];
textView1.editable = NO;//不允许编辑
textView1.font = [UIFont systemFontOfSize:20];
textView1.text = @"只检测手机号------\r\n我的手机号不是: 13666666666 \r\n\r\n"
"我的博客网址: www.ppsheep.com \r\n\r\n"
"我的邮箱: 787688073@qq.com \r\n\r\n";
textView1.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
[self.view addSubview:textView1];


//UIDataDetectorType  是将网址和邮箱一起检测  点击能够相应地进入操作
UITextView *textView2 = [[UITextView alloc] initWithFrame:CGRectMake(10, 250, self.view.frame.size.width, 200)];
textView2.font = [UIFont systemFontOfSize:20];
textView2.editable = NO;
textView2.text = @"只检测网址和邮箱------\r\n我的手机号不是: 13666666666 \r\n\r\n"
"我的博客网址: www.ppsheep.com \r\n\r\n"
"我的邮箱: 787688073@qq.com \r\n\r\n";
textView2.dataDetectorTypes = UIDataDetectorTypeLink;
[self.view addSubview:textView2];

看一下效果