开发过程中,往往会用到一些常见又通用的方法,整个工程中我们可能需要多次用到,或者多个工程中会用到相同的方法。比如判断手机号、邮箱的合法性,在登录或者注册相关页面,我们都需要用到相应的方法去判断,而如果我们每次都写一个判断方法的话,代码会显得尤其的冗余,这时候我们可以将这些方法都封装起来,这样每次使用的时候,直接调用相关的方法即可。在不同的工程之间也能进行复用。还有一些常见的小功能实现很简单,但是我们可能不经常用,所以需要的时候未必能及时记起来。面对这样的情况,我们可以将这些方法记录起来,需要的时候,直接拿出来看一看就能知道如何实现了。今天呢,主要就收集一些常见通用的好东西,本文会不定时更新,同时也欢迎大家补充。
内容有:
字符串部分:
1、手机号码匹配
2、邮箱匹配
3、base64加密
4、时间戳转换成指定格式的日期
5、日期转换成时间戳
6、判断输入的是否是有效数字
其他部分:
1、 十六进制颜色转换成UIColor
2、UITextField截断指定长度的字符串
3、打开手机qq与指定人聊天
4、拨打电话
5、加载启动图的时候如何隐藏statusbar
一、关于NSString的一些常用方法。
这部分我们可以对NSString写一个类目,这样我们导入这个类目后,调用相关的方法即可。创建类目 NSString (CategoryMethods)
1、手机号码匹配
声明方法:
-(BOOL)isMobileNumber:(NSString *)mobileNum ;
实现该方法:
// 正则判断手机号码地址格式
- (BOOL)isMobileNumber:(NSString *)mobileNum {
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0135678])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:mobileNum];
}```
#####*2、邮箱匹配*
声明方法:
`- (BOOL)isValidateEmail:(NSString *)email;`
实现该方法:
//邮箱
-(BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}
#####*3、base64加密*
声明方法:
`- (NSString *)base64;`
实现该方法:
-
(NSString *)base64 {
NSData *data = [NSData dataWithBytes:[self UTF8String] length:[self lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSUInteger length = [data length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; NSUInteger idx = (i / 3) * 4; output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
#####*4、时间戳转换成指定格式的日期*
声明方法:
`
-(NSString *)getDateStringWithTimeInterval:(NSString *)timeInterval DataFormatterString:(NSString *)dataFormatterString;`
实现该方法:
pragma mark--时间戳转换成日期
-(NSString *)getDateStringWithTimeInterval:(NSString *)timeInterval DataFormatterString:(NSString *)dataFormatterString{
NSString *dateString;
NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
dataFormatter.dateFormat = dataFormatterString;
NSTimeInterval _interval=[timeInterval doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
dateString = [dataFormatter stringFromDate:date];
return dateString;
}
#####*5、日期转换成时间戳*
声明方法:
`
-(double)getTimeIntervalWithDateString:(NSString *)dateString DataFormatterString:(NSString *)dataFormatterString;`
实现该方法:
-(double)getTimeIntervalWithDateString:(NSString *)dateString DataFormatterString:(NSString *)dataFormatterString{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:dataFormatterString];
NSDate* date = [formatter dateFromString:dateString];
//将日期转换成时间戳
double timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] doubleValue]*1000;
return timeSp;
}
#####*6、判断输入的是否是有效数字*
声明方法
`-(BOOL)isValidNumber:(NSString *)str`
现实方法
-(BOOL)isAvildNumber:(NSString *)str{
NSString string=@"^[1-9][0-9](\.[0-9]+)?$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
return [regextestmobile evaluateWithObject:str];
}
###二、将十六进制颜色转换成UIColor。
十六进制颜色的转换,我们也可以通过对UIColor写一个类目来实现。
声明方法:
`+ (UIColor *)colorWithHex: (NSString *)color;`
`+ (UIColor *)colorWithHex: (NSString *)color alpha:(CGFloat)alpha;`
实现方法:
//颜色透明度默认为1
-
(UIColor *)colorWithHex:(NSString *)color {
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// strip 0X if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
//自定义颜色透明度
-
(UIColor *)colorWithHex:(NSString *)color alpha:(CGFloat)alpha{
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// strip 0X if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}
###三、UITextField截断字符串。
为`UITextField`写一个类目`LimitTextLength`,指定长度,超过指定长度时截断。
声明方法:
`
-(void)limitTextLength:(NSInteger)length TextField:(UITextField *)textfield;`
实现该方法:
-(void)limitTextLength:(NSInteger)length TextField:(UITextField *)textfield{
NSString *toBeString = textfield.text;
NSString *lang = self.textInputMode.primaryLanguage;
if ([lang isEqualToString:@"zh-Hans"]) {
UITextRange *selectedRang = [textfield markedTextRange];
if (!selectedRang) {
if (toBeString.length > length) {
textfield.text = [toBeString substringToIndex:length];
}
}else{
}
}
else{
if (toBeString.length > length) {
textfield.text = [toBeString substringToIndex:length];
}
}
}
如何使用该方法呢?
1.导入创建好的类目`UITextField+LimitTextLength.h`后,我们创建一个`UITextField`,并为其注册text发生变化的通知`UITextFieldTextDidChangeNotification`
_textFieid=[[UITextField alloc] initWithFrame:CGRectMake(20, 240, self.view.frame.size.width-40, 50)];
[self.view addSubview:_textFieid];
_textFieid.layer.borderWidth=.5;
_textFieid.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:_textFieid];
2、实现通知方法:
-(void)textFieldEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
if (textField == _textFieid) {
[_textFieid limitTextLength:10 TextField:_textFieid];
}
}
###四、打开手机qq与指定人聊天。
这个是通过web网页的方法调起qq客户端,需要配置LSApplicationQueriesSchemes
-(void)didClickQQButton{
//需要在info.plist中增加LSApplicationQueriesSchemes数组,然后添加item0,item0对应的值为mqqapi;增加item1,item1的值为mqq。
NSString * QQNumber=@"";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web", QQNumber]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
webView.delegate = self;
[webView loadRequest:request];
[self.view addSubview:webView];
}else{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"nil" message:@"对不起,您还没安装QQ" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
return ;
}];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
}
}
###五、拨打电话。
-(void)didClickPhoneButton{
NSString PhoneNumber=@"";
NSMutableString str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@", PhoneNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] ];
}
###六、如何在加载启动图的时候将statusBar隐藏掉
如果你觉得加载启动图的时候,显示statusBar不好看,想把它隐藏起来的话,只需需要在info.plist中加入`Status bar is initially hidden `设置为YES就好了。
###[demo](https://github.com/wxzwork/iOS-commonMethod)
网友评论