在开发应用的过程中几乎所有的app都会用到的一些方法,现在记录下来,以便以后查看。
- 等比缩放图片
+ (UIImage *)changeImageSize:(NSString *)imageName withScale:(CGFloat)scale {
NSData *imgData = UIImagePNGRepresentation([UIImage imageNamed:imageName]);
UIImage * image = [UIImage imageWithData:imgData scale:scale];
//声明使用自定义的图片
//image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
return image;
}
- 把url进行NSUTF8StringEncoding 返回
+ (NSString *)urlStringToUTF8StringEncodingWithString:(NSString *)originalUrl {
if (originalUrl.length) {
if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
originalUrl = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
} else {
originalUrl = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
}
return originalUrl;
}
- 动态返回字符串的CGSize (包括宽高)
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW {
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = font;
CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
4.跳转到iOS系统的设置页
+ (void)pushToSystemSettingView {
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
if (([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0)) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
} else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
}
}
- 把字符串的某一部分用‘*’代替(如:李大佬 => *大佬, 1588888888 -> 158*******)
+ (NSString *)replaceStringWithAsterisk:(NSString *)originalStr startLocation:(NSInteger)startLocation lenght:(NSInteger)lenght {
NSString *newStr = originalStr;
for (int i = 0; i < lenght; i++) {
NSRange range = NSMakeRange(startLocation, 1);
newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
startLocation ++;
}
return newStr;
}
- 字典转字符串/ 字符串转字典
// 字典转字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
if (dic) {
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return nil;
}
// 字符串字典转 字典
+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
if (JSONString.length > 0) {
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
return responseJSON;
}
return [NSDictionary dictionary];
}
- 获取当前的时间戳 / 传入秒得到XX分钟和XX秒
+ (NSString *)getCurrentTime { // 保存打开应用的时间戳
NSDate * senddate = [NSDate date];
NSString * currentDate = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
NSLog(@"%@", currentDate);
return currentDate;
}
//传入秒得到 xx分钟xx秒
+ (NSString *)getMMSSFromSS:(NSString *)totalTime {
NSInteger seconds = [totalTime integerValue];
NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
NSLog(@"format_time : %@",format_time);
return format_time;
}
- 正则判断手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
if (mobileNum.length != 11) return NO;
NSString * MOBILE = @"^1(3|4|5|7|8)\\d{9}$";//@"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$"; // ^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$
NSPredicate * regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:mobileNum];
}
- 判断只能输入数字
/*** 判断只能输入数字 **/
#define NUMBERS @"0123456789\n"
+ (BOOL)limitIputNumberWithText:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if(!basicTest) {
return NO;
}
return YES;
}
10.判断中文名字
+ (BOOL)isVaildRealName:(NSString *)realName {
if ([self checkEmptyString:realName]) return NO;
NSRange range1 = [realName rangeOfString:@"·"];
NSRange range2 = [realName rangeOfString:@"•"];
if(range1.location != NSNotFound || // 中文 ·
range2.location != NSNotFound ) // 英文 •
{
//一般中间带 `•`的名字长度不会超过15位,如果有那就设高一点
if ([realName length] < 2 || [realName length] > 15)
{
return NO;
}
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+[·•][\u4e00-\u9fa5]+$" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:realName options:0 range:NSMakeRange(0, [realName length])];
NSUInteger count = [match numberOfRanges];
return count == 1;
} else {
//一般正常的名字长度不会少于2位并且不超过8位,如果有那就设高一点
if ([realName length] < 2 || [realName length] > 8) {
return NO;
}
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+$" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:realName options:0 range:NSMakeRange(0, [realName length])];
NSUInteger count = [match numberOfRanges];
return count == 1;
}
}
+ (BOOL)checkEmptyString:(NSString *)string {
if (string == nil) return string == nil;
NSString *newStr = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
return [newStr isEqualToString:@""];
}
- 正则判断身份证号
//正则匹配用户身份证号15或18位
+ (BOOL)validateIDCardNumber:(NSString *)value {
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSInteger length =0;
if (!value) {
return NO;
}else {
length = value.length;
//不满足15位和18位,即身份证错误
if (length !=15 && length !=18) {
return NO;
}
}
// 省份代码
NSArray *areasArray = @[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
// 检测省份身份行政区代码
NSString *valueStart2 = [value substringToIndex:2];
BOOL areaFlag =NO; //标识省份代码是否正确
for (NSString *areaCode in areasArray) {
if ([areaCode isEqualToString:valueStart2]) {
areaFlag =YES;
break;
}
}
if (!areaFlag) {
return NO;
}
NSRegularExpression *regularExpression;
NSUInteger numberofMatch;
int year =0;
//分为15位、18位身份证进行校验
switch (length) {
case 15:
//获取年份对应的数字
year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
//创建正则表达式 NSRegularExpressionCaseInsensitive:不区分字母大小写的模式
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}else {
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
//使用正则表达式匹配字符串 NSMatchingReportProgress:找到最长的匹配字符串后调用block回调
numberofMatch = [regularExpression numberOfMatchesInString:value
options:NSMatchingReportProgress
range:NSMakeRange(0, value.length)];
if(numberofMatch >0) {
return YES;
}else {
return NO;
}
case 18:
year = [value substringWithRange:NSMakeRange(6,4)].intValue;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}else {
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
numberofMatch = [regularExpression numberOfMatchesInString:value
options:NSMatchingReportProgress
range:NSMakeRange(0, value.length)];
if(numberofMatch >0) {
int S = [value substringWithRange:NSMakeRange(0,1)].intValue*7 + [value substringWithRange:NSMakeRange(10,1)].intValue *7 + [value substringWithRange:NSMakeRange(1,1)].intValue*9 + [value substringWithRange:NSMakeRange(11,1)].intValue *9 + [value substringWithRange:NSMakeRange(2,1)].intValue*10 + [value substringWithRange:NSMakeRange(12,1)].intValue *10 + [value substringWithRange:NSMakeRange(3,1)].intValue*5 + [value substringWithRange:NSMakeRange(13,1)].intValue *5 + [value substringWithRange:NSMakeRange(4,1)].intValue*8 + [value substringWithRange:NSMakeRange(14,1)].intValue *8 + [value substringWithRange:NSMakeRange(5,1)].intValue*4 + [value substringWithRange:NSMakeRange(15,1)].intValue *4 + [value substringWithRange:NSMakeRange(6,1)].intValue*2 + [value substringWithRange:NSMakeRange(16,1)].intValue *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
int Y = S %11;
NSString *M =@"F";
NSString *JYM =@"10X98765432";
M = [JYM substringWithRange:NSMakeRange(Y,1)];
if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
return YES;
} else {
return NO;
}
} else {
return NO;
}
default:
return NO;
}
}
- 修改UITextField的提示文字的颜色和大小
[textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];//修改颜色
[textField setValue:[UIFontsystemFontOfSize:11]forKeyPath:@"_placeholderLabel.font"];//修改字体