1.)设置Label字体不同颜色
// string 为要改变颜色的字段
- (void)setDifferentColorWithLabel:(UILabel *)label string:(NSString *)string {
NSMutableAttributedString *noteStr =[[NSMutableAttributedString alloc]initWithString:label.text];
NSRange stringRange = NSMakeRange([[noteStr string] rangeOfString:string].location, [[noteStr string] rangeOfString:string].length);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:stringRange];
//改变特定字段的大小
[noteStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:stringRange];
[label setAttributedText:noteStr];
[label sizeToFit];
}
2.) 数组内计算
- (void)calculateInArray:(NSArray *)array {
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
}
3.) 判断是否是整形
- (BOOL)isIntClass:(NSString *)string {
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
if(string.length > 0){
return NO;
}
return YES;
}
4.) 多个字符一起切割字符串
//以a和c分割字符串
[self divideString:@"tingabcdefghiajklmnopcqrstuvwxayz" words:@"ac"];
- (NSArray *)divideString:(NSString *)string words:(NSString *)str {
NSCharacterSet *set =[NSCharacterSet characterSetWithCharactersInString:str];
NSArray *array0 =[string componentsSeparatedByCharactersInSet:set];
return array0 ;
}
5.) 将十六进制的颜色转换为UIColor
+ (UIColor *)getColor:(NSString *)str {
NSString *cString = [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([cString length] < 6){
return [UIColor clearColor];
}
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
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];
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];
}
6.) 比较日期大小
/************
日期格式请传入:2016-11-30 12:12:12;如果修改日期格式,比如:2013-08-05,则将[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];修改为[df setDateFormat:@"yyyy-MM-dd"];
***********/
+ (int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
int value;
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dt1 = [[NSDate alloc]init];
NSDate *dt2 = [[NSDate alloc]init];
dt1 = [df dateFromString:date01];
dt2 = [df dateFromString:date02];
NSComparisonResult result = [dt1 compare:dt2];
switch (result) {
//date02比date01大
case NSOrderedAscending:
value=1;break;
//date02比date01小
case NSOrderedDescending:
value=-1;break;
//date02=date01
case NSOrderedSame:
value=0;break;
default:
NSLog(@"erorr dates %@, %@", dt2, dt1);break;
}
return value;
}
7.) 将日期转化为周天数
//传入的是 2017-05-06 格式的字符串 若是已经格式化的,请去掉下面格式化的代码
+ (NSString*)getWeekDay:(NSString*)currentStr{
NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate*date =[dateFormat dateFromString:currentStr];
NSArray*weekdays = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
NSCalendar*calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSTimeZone*timeZone = [[NSTimeZone alloc]initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSCalendarUnit calendarUnit =NSCalendarUnitWeekday;
NSDateComponents*theComponents = [calendar components:calendarUnit fromDate:date];
return[weekdays objectAtIndex:theComponents.weekday-1];
}
8.) 弹出透明VC
//方法一
- (void)presentClearVCMthod1{
TestVC1* testVC1 =[[TestVC1 alloc]init];
[self addChildViewController:testVC1];
testVC1.string =@"Mars";
// 若这里的传值写在设置frame之后,将在viewload里接收不到,因为先viewdidload先执行,后传值
testVC1.view.frame =CGRectMake(0, 0,ScreenW, ScreenH);
// ScreenW,ScreenH 为屏宽高的宏。
[self.view addSubview:testVC1.view];
}
//方法二
//将animated设为NO就有弹框的效果
- (void)presentClearVCMethod2 {
TestVC2 *testVC2 = [[TestVC2 alloc]init];
self.definesPresentationContext =YES;
testVC2.modalPresentationStyle =UIModalPresentationOverCurrentContext;
[self presentViewController:testVC2 animated:NO completion:nil];
}
9.) 计算文件夹大小
//遍历文件夹获得文件夹大小,返回单位为 M
- (float)folderSizeAtPath:(NSString*)folderPath{
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
10.) APP内拨打电话
- (void)dailPhone:(NSString *)phoneNum {
NSString * str=[[NSString alloc] initWithFormat:@"telprompt://%@",phoneNum];
//ios 10
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
//ios 10 之后
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:url] options:@{UIApplicationOpenURLOptionsSourceApplicationKey : @YES} completionHandler:^(BOOL success) {
//成功后的回调
if (!success) {
//失败后的回调
}
}];
}
11.) 跳转到设置界面
- (void)gotoSettingPage {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplication sharedApplication] canOpenURL:url]) {
NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}
}
12.) 检测字符串是否包含表情
+ (BOOL)stringContainsEmoji:(NSString *)string{
__block BOOL returnValue = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
if (0xd800 <= hs && hs <= 0xdbff) {
if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f) {
returnValue = YES;
}
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3) {
returnValue = YES;
}
} else {
if (0x2100 <= hs && hs <= 0x27ff) {
returnValue = YES;
} else if (0x2B05 <= hs && hs <= 0x2b07) {
returnValue = YES;
} else if (0x2934 <= hs && hs <= 0x2935) {
returnValue = YES;
} else if (0x3297 <= hs && hs <= 0x3299) {
returnValue = YES;
} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
returnValue = YES;
}else if (hs == 0x200d){
returnValue = YES;
}
}
}];
return returnValue;
}
13.) 删除NSUserDefaults所有记录
//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults {
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
}
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
14.) 禁止屏幕睡眠
//APP内长时间不接触屏幕会锁屏,有些需求需要保持屏幕常亮,比如播放视频等
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
15.) 修改占位符的属性
//方法一
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
//方法二
NSDictionary *dic=@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:16]};
textField.attributedPlaceholder=[[NSAttributedString alloc]initWithString:@"请输入手机号/账号" attributes:Dic];
16.) 压缩图片
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return UIImageJPEGRepresentation(newImage, 0.8);
}
17.) 随机生成指定位数的数字和字母的组合字符串
- (NSString *)getRandomStringWithNum:(NSInteger)num {
NSString *string = [[NSString alloc]init];
for (int i = 0; i < num; i++) {
int number = arc4random() % 36;
if (number < 10) {
int figure = arc4random() % 10;
NSString *tempString = [NSString stringWithFormat:@"%d", figure];
string = [string stringByAppendingString:tempString];
}else {
int figure = (arc4random() % 26) + 97;
char character = figure;
NSString *tempString = [NSString stringWithFormat:@"%c", character];
string = [string stringByAppendingString:tempString];
}
}
return string;
}
18.) 获取APP相关信息
//获取版本号
NSString *version=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//获取Build号
NSString *build=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
//获取设备的UUID
NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];