- 獲取磁盤總空間大小
<pre>//磁盤總空間
- (CGFloat)diskOfAllSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemSize];
size = [number floatValue]/1024/1024;
}
return size;
}
</pre>
- 獲取磁盤可用空間大小
<pre>//磁盤可用空間
- (CGFloat)diskOfFreeSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
size = [number floatValue]/1024/1024;
}
return size;
}
</pre>
- 獲取指定路徑下某個文件的大小
<pre>//獲取文件大小
- (long long)fileSizeAtPath:(NSString *)filePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) return 0;
return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
}
</pre>
- 獲取文件夾下所有文件的大小
<pre>//獲取文件夾下所有文件的大小
- (long long)folderSizeAtPath:(NSString *)folderPath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
NSString *fileName;
long long folerSize = 0;
while ((fileName = [filesEnumerator nextObject]) != nil) {
NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
folerSize += [self fileSizeAtPath:filePath];
}
return folerSize;
}
</pre>
- 獲取字符串(或漢字)首字母
<pre>//獲取字符串(或漢字)首字母
- (NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
}
</pre>
- 將字符串數組按照元素首字母順序進行排序分組
<pre>//將字符串數組按照元素首字母順序進行排序分組
- (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
if (array.count == 0) {
return nil;
}
for (id obj in array) {
if (![obj isKindOfClass:[NSString class]]) {
return nil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
//創建27個分組數組
for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *obj = [NSMutableArray array];
[objects addObject:obj];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母順序進行分組
NSInteger lastIndex = -1;
for (int i = 0; i < array.count; i++) {
NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
[[objects objectAtIndex:index] addObject:array[i]];
lastIndex = index;
}
//去掉空數組
for (int i = 0; i < objects.count; i++) {
NSMutableArray *obj = objects[i];
if (obj.count == 0) {
[objects removeObject:obj];
}
}
//獲取索引字母
for (NSMutableArray *obj in objects) {
NSString *str = obj[0];
NSString *key = [self firstCharacterWithString:str];
[keys addObject:key];
}
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:objects forKey:keys];
return dic;
}
//獲取字符串(或漢字)首字母
- (NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
</pre>
- 獲取當前時間
<pre>//獲取當前時間
//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH時mm分ss秒"
- (NSString *)currentDateWithFormat:(NSString *)format{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
return [dateFormatter stringFromDate:[NSDate date]];
}
</pre>
- 計算上次日期距離現在多久, 如 xx 小時前、xx 分鐘前等
<pre>/**
- 計算上次日期距離現在多久
- @param lastTime 上次日期(需要和格式對應)
- @param format1 上次日期格式
- @param currentTime 最近日期(需要和格式對應)
- @param format2 最近日期格式
- @return xx分鐘前、xx小時前、xx天前
*/
(NSString *)timeIntervalFromLastTime:(NSString *)lastTime
lastTimeFormat:(NSString *)format1
ToCurrentTime:(NSString *)currentTime
currentTimeFormat:(NSString *)format2{
//上次時間
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
dateFormatter1.dateFormat = format1;
NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
//當前時間
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
dateFormatter2.dateFormat = format2;
NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
}-
(NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
//上次時間
NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
//當前時間
NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
//時間間隔
NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];//秒、分、小時、天、月、年
NSInteger minutes = intevalTime / 60;
NSInteger hours = intevalTime / 60 / 60;
NSInteger day = intevalTime / 60 / 60 / 24;
NSInteger month = intevalTime / 60 / 60 / 24 / 30;
NSInteger yers = intevalTime / 60 / 60 / 24 / 365;if (minutes <= 10) {
return @"剛剛";
}else if (minutes < 60){
return [NSString stringWithFormat: @"%ld分鐘前",(long)minutes];
}else if (hours < 24){
return [NSString stringWithFormat: @"%ld小時前",(long)hours];
}else if (day < 30){
return [NSString stringWithFormat: @"%ld天前",(long)day];
}else if (month < 12){
NSDateFormatter * df =[[NSDateFormatter alloc]init];
df.dateFormat = @"M月d日";
NSString * time = [df stringFromDate:lastDate];
return time;
}else if (yers >= 1){
NSDateFormatter * df =[[NSDateFormatter alloc]init];
df.dateFormat = @"yyyy年M月d日";
NSString * time = [df stringFromDate:lastDate];
return time;
}
return @"";
}
</pre>
- 判斷手機號碼格式是否正確
<pre>//判斷手機號碼格式是否正確
-
(BOOL)valiMobile:(NSString )mobile{
mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
if (mobile.length != 11)
{
return NO;
}else{
/*
* 移動號段正則表達式
/
NSString CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\d{8}|(1705)\d{7}$";
/
* 聯通號段正則表達式
/
NSString CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\d{8}|(1709)\d{7}$";
/
* 電信號段正則表達式
*/
NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\d{8}$";
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
BOOL isMatch3 = [pred3 evaluateWithObject:mobile];if (isMatch1 || isMatch2 || isMatch3) { return YES; }else{ return NO; }
}
}
</pre>
- 判斷郵箱格式是否正確
<pre>//利用正則表達式驗證
- (BOOL)isAvailableEmail:(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];
}
</pre>
- 將十六進制顏色轉換為 UIColor 對象
<pre>//將十六進制顏色轉換為 UIColor 對象
- (UIColor *)colorWithHexString:(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" or "#" 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];
}
</pre>
- 對圖片進行濾鏡處理
<pre>#pragma mark - 對圖片進行濾鏡處理
// 懷舊 --> CIPhotoEffectInstant 單色 --> CIPhotoEffectMono
// 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade
// 色調 --> CIPhotoEffectTonal 沖印 --> CIPhotoEffectProcess
// 歲月 --> CIPhotoEffectTransfer 鉻黃 --> CIPhotoEffectChrome
// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
- (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:name];
[filter setValue:inputImage forKey:kCIInputImageKey];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return resultImage;
}
</pre>
- 對圖片進行模糊處理
<pre>#pragma mark - 對圖片進行模糊處理
// CIGaussianBlur ---> 高斯模糊
// CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later)
// CIDiscBlur ---> 環形卷積模糊(Available in iOS 9.0 and later)
// CIMedianFilter ---> 中值模糊, 用于消除圖像噪點, 無需設置radius(Available in iOS 9.0 and later)
// CIMotionBlur ---> 運動模糊, 用于模擬相機移動拍攝時的掃尾效果(Available in iOS 9.0 and later)
- (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter;
if (name.length != 0) {
filter = [CIFilter filterWithName:name];
[filter setValue:inputImage forKey:kCIInputImageKey];
if (![name isEqualToString:@"CIMedianFilter"]) {
[filter setValue:@(radius) forKey:@"inputRadius"];
}
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return resultImage;
}else{
return nil;
}
}
</pre>
- 調整圖片飽和度、亮度、對比度
<pre>/**
- 調整圖片飽和度, 亮度, 對比度
- @param image 目標圖片
- @param saturation 飽和度
- @param brightness 亮度: -1.0 ~ 1.0
- @param contrast 對比度
*/
-
(UIImage *)colorControlsWithOriginalImage:(UIImage *)image
saturation:(CGFloat)saturation
brightness:(CGFloat)brightness
contrast:(CGFloat)contrast{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
[filter setValue:inputImage forKey:kCIInputImageKey];[filter setValue:@(saturation) forKey:@"inputSaturation"];
[filter setValue:@(brightness) forKey:@"inputBrightness"];
[filter setValue:@(contrast) forKey:@"inputContrast"];CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return resultImage;
}
</pre>
- 創建一張實時模糊效果 View (毛玻璃效果)
<pre>//Avilable in iOS 8.0 and later
- (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
effectView.frame = frame;
return effectView;
}
</pre>
- 全屏截圖
<pre>//全屏截圖
- (UIImage *)shotScreen{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIGraphicsBeginImageContext(window.bounds.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
</pre>
- 截取一張 view 生成圖片
<pre>//截取view生成一張圖片
- (UIImage *)shotWithView:(UIView *)view{
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
</pre>
- 截取view中某個區域生成一張圖片
<pre>//截取view中某個區域生成一張圖片
- (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
UIGraphicsBeginImageContext(scope.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
CGContextTranslateCTM(context, 0, rect.size.height);//下移
CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
CGContextDrawImage(context, rect, imageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(imageRef);
CGContextRelease(context);
return image;
}
</pre>
- 壓縮圖片到指定尺寸大小
<pre>//壓縮圖片到指定尺寸大小
- (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
UIImage *resultImage = image;
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIGraphicsEndImageContext();
return resultImage;
}
</pre>
- 壓縮圖片到指定文件大小
<pre>//壓縮圖片到指定文件大小
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
NSData *data = UIImageJPEGRepresentation(image, 1.0);
CGFloat dataKBytes = data.length/1000.0;
CGFloat maxQuality = 0.9f;
CGFloat lastData = dataKBytes;
while (dataKBytes > size && maxQuality > 0.01f) {
maxQuality = maxQuality - 0.01f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length/1000.0;
if (lastData == dataKBytes) {
break;
}else{
lastData = dataKBytes;
}
}
return data;
}
</pre>
- 獲取設備 IP 地址
需要先引入下頭文件:
Objective-C
1
2
import <ifaddrs.h>
import <arpa/inet.h>
<pre>//獲取設備 IP 地址
- (NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}
</pre>
- 判斷字符串中是否含有空格
<pre>+ (BOOL)isHaveSpaceInString:(NSString *)string{
NSRange _range = [string rangeOfString:@" "];
if (_range.location != NSNotFound) {
return YES;
}else {
return NO;
}
}
</pre>
- 判斷字符串中是否含有某個字符串
<pre>+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{
NSRange _range = [string2 rangeOfString:string1];
if (_range.location != NSNotFound) {
return YES;
}else {
return NO;
}
}
</pre>
- 判斷字符串中是否含有中文
<pre>+ (BOOL)isHaveChineseInString:(NSString *)string{
for(NSInteger i = 0; i < [string length]; i++){
int a = [string characterAtIndex:i];
if (a > 0x4e00 && a < 0x9fff) {
return YES;
}
}
return NO;
}
</pre>
- 判斷字符串是否全部為數字
<pre>+ (BOOL)isAllNum:(NSString *)string{
unichar c;
for (int i=0; i<string.length; i++) {
c=[string characterAtIndex:i];
if (!isdigit(c)) {
return NO;
}
}
return YES;
}
</pre>
- 繪制虛線
<pre>/*
** lineFrame: 虛線的 frame
** length: 虛線中短線的寬度
** spacing: 虛線中短線之間的間距
** color: 虛線中短線的顏色
*/
- (UIView *)createDashedLineWithFrame:(CGRect)lineFrame
lineLength:(int)length
lineSpacing:(int)spacing
lineColor:(UIColor *)color{
UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];
dashedLine.backgroundColor = [UIColor clearColor];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:dashedLine.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
[shapeLayer setStrokeColor:color.CGColor];
[shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
[dashedLine.layer addSublayer:shapeLayer];
return dashedLine;
}
</pre>
1,打印View所有子視圖
<pre>po [[self view]recursiveDescription]</pre>
2,layoutSubviews調用的調用時機
<pre>* 當視圖第一次顯示的時候會被調用
- 當這個視圖顯示到屏幕上了,點擊按鈕
- 添加子視圖也會調用這個方法
- 當本視圖的大小發生改變的時候是會調用的
- 當子視圖的frame發生改變的時候是會調用的
- 當刪除子視圖的時候是會調用的</pre>
3,NSString過濾特殊字符
<pre>// 定義一個特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-+=|~<>$€?'@#$%&*()+'""];
// 過濾字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];</pre>
4,TransForm屬性
<pre>//平移按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);
//旋轉按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);
//縮放按鈕
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);
//初始化復位
self.buttonView.transform = CGAffineTransformIdentity;</pre>
5,去掉分割線多余15像素
<pre>首先在viewDidLoad方法加入以下代碼:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
然后在重寫willDisplayCell方法
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}</pre>
6,計算方法耗時時間間隔
<pre>// 獲取時間間隔
define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)</pre>
7,Color顏色宏定義
<pre>// 隨機顏色
define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
// 顏色(RGB)
define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
// 利用這種方法設置顏色和透明值,可不影響子視圖背景色
define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
</pre>
8,Alert提示宏定義
<pre>- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished) {
exit(0);
}];
}</pre>
9,NSArray 快速求總和 最大值 最小值 和 平均值
<pre>NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
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(@"%fn%fn%fn%f",sum,avg,max,min);
</pre>
10修改Label中不同文字顏色
<pre>- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}
-
(void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color {
// string為整體字符串, editStr為需要修改的字符串
NSRange range = [string rangeOfString:editStr];NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string];
// 設置屬性修改字體顏色UIColor與大小UIFont
[attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];self.label.attributedText = attribute;
}</pre>
10,播放聲音
<pre>#import
// 1.獲取音效資源的路徑
NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
// 2.將路勁轉化為url
NSURL *tempUrl = [NSURL fileURLWithPath:path];
// 3.用轉化成的url創建一個播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self.player = play;
// 4.播放
[play play];</pre>
11檢測是否IPad Pro和其它設備型號
<pre>- (BOOL)isIpadPro
{
UIScreen *Screen = [UIScreen mainScreen];
CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;
BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
BOOL hasIPadProWidth = fabs(width - 1024.f) = 8.0)</pre>
12修改Tabbar Item的屬性
// 修改標題位置
self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
// 修改圖片位置
self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);
// 批量修改屬性
for (UIBarItem *item in self.tabBarController.tabBar.items) {
[item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
forState:UIControlStateNormal];
}
// 設置選中和未選中字體顏色
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
//未選中字體顏色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];
//選中字體顏色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];
12,NULL – nil – Nil – NSNULL的區別
<pre>* nil是OC的,空對象,地址指向空(0)的對象。對象的字面零值
Nil是Objective-C類的字面零值
NULL是C的,空地址,地址的數值是0,是個長整數
NSNull用于解決向NSArray和NSDictionary等集合中添加空值的問題</pre>
11,去掉BackBarButtonItem的文字
<pre>[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault]</pre>
12,控件不能交互的一些原因
<pre>1,控件的userInteractionEnabled = NO
2,透明度小于等于0.01,aplpha
3,控件被隱藏的時候,hidden = YES
4,子視圖的位置超出了父視圖的有效范圍,子視圖無法交互,設置了。
5,需要交互的視圖,被其他視圖蓋住(其他視圖開啟了用戶交互)。</pre>
12,修改UITextField中Placeholder的文字顏色
<pre>[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}</pre>
13,視圖的生命周期
<pre>1、 alloc 創建對象,分配空間
2、 init (initWithNibName) 初始化對象,初始化數據
3、 loadView 從nib載入視圖 ,除非你沒有使用xib文件創建視圖
4、 viewDidLoad 載入完成,可以進行自定義數據以及動態創建其他控件
5、 viewWillAppear視圖將出現在屏幕之前,馬上這個視圖就會被展現在屏幕上了
6、 viewDidAppear 視圖已在屏幕上渲染完成
1、viewWillDisappear 視圖將被從屏幕上移除之前執行
2、viewDidDisappear 視圖已經被從屏幕上移除,用戶看不到這個視圖了
3、dealloc 視圖被銷毀,此處需要對你在init和viewDidLoad中創建的對象進行釋放.
viewVillUnload- 當內存過低,即將釋放時調用;
viewDidUnload-當內存過低,釋放一些不需要的視圖時調用。</pre>
14,應用程序的生命周期
<pre>1,啟動但還沒進入狀態保存 :
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
2,基本完成程序準備開始運行:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
3,當應用程序將要入非活動狀態執行,應用程序不接收消息或事件,比如來電話了:
- (void)applicationWillResignActive:(UIApplication *)application
4,當應用程序入活動狀態執行,這個剛好跟上面那個方法相反:
- (void)applicationDidBecomeActive:(UIApplication *)application
5,當程序被推送到后臺的時候調用。所以要設置后臺繼續運行,則在這個函數里面設置即可:
- (void)applicationDidEnterBackground:(UIApplication *)application
6,當程序從后臺將要重新回到前臺時候調用,這個剛好跟上面的那個方法相反:
- (void)applicationWillEnterForeground:(UIApplication *)application
7,當程序將要退出是被調用,通常是用來保存數據和一些退出前的清理工作:
- (void)applicationWillTerminate:(UIApplication *)application
</pre>
15,判斷view是不是指定視圖的子視圖
<pre> BOOL isView = [textView isDescendantOfView:self.view];
</pre>
16,判斷對象是否遵循了某協議
<pre>if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) {
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}</pre>
17,頁面強制橫屏
<pre>#pragma mark - 強制橫屏代碼
- (BOOL)shouldAutorotate{
//是否支持轉屏
return NO;
} - (UIInterfaceOrientationMask)supportedInterfaceOrientations{
//支持哪些轉屏方向
return UIInterfaceOrientationMaskLandscape;
} - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return UIInterfaceOrientationLandscapeRight;
} - (BOOL)prefersStatusBarHidden{
return NO;
}</pre>
18,系統鍵盤通知消息
<pre>1、UIKeyboardWillShowNotification-將要彈出鍵盤
2、UIKeyboardDidShowNotification-顯示鍵盤
3、UIKeyboardWillHideNotification-將要隱藏鍵盤
4、UIKeyboardDidHideNotification-鍵盤已經隱藏
5、UIKeyboardWillChangeFrameNotification-鍵盤將要改變frame
6、UIKeyboardDidChangeFrameNotification-鍵盤已經改變frame</pre>
19,關閉navigationController的滑動返回手勢
<pre>self.navigationController.interactivePopGestureRecognizer.enabled = NO;</pre>
20,設置狀態欄背景為任意的顏色
<pre>- (void)setStatusColor
{
UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
statusBarView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:statusBarView];
}</pre>
22,Label行間距
<pre>-(void)test{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
//調整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}
</pre>
23,UIImageView填充模式
<pre>@"UIViewContentModeScaleToFill", // 拉伸自適應填滿整個視圖
@"UIViewContentModeScaleAspectFit", // 自適應比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下</pre>
24,宏定義檢測block是否可用
<pre>#define BLOCK_EXEC(block, ...) if (block) { block(VA_ARGS); };
// 宏定義之前的用法
if (completionBlock) {
completionBlock(arg1, arg2);
}
// 宏定義之后的用法
BLOCK_EXEC(completionBlock, arg1, arg2);</pre>
25,Debug欄打印時自動把Unicode編碼轉化成漢字
<pre>// 有時候我們在xcode中打印中文,會打印出Unicode編碼,還需要自己去一些在線網站轉換,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin 插件</pre>
26,設置狀態欄文字樣式顏色
<pre>[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];</pre>
26,自動生成模型代碼的插件
<pre>
可自動生成模型的代碼,省去寫模型代碼的時間
ESJsonFormat-for-Xcode</pre>
27,iOS中的一些手勢
<pre>輕擊手勢(TapGestureRecognizer)
輕掃手勢(SwipeGestureRecognizer)
長按手勢(LongPressGestureRecognizer)
拖動手勢(PanGestureRecognizer)
捏合手勢(PinchGestureRecognizer)
旋轉手勢(RotationGestureRecognizer)</pre>
27,iOS 開發中一些相關的路徑
<pre>模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs
文檔安裝位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets
插件保存路徑:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins
自定義代碼段的保存路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夾,可以自己新建一個CodeSnippets文件夾。
證書路徑
~/Library/MobileDevice/Provisioning Profiles
</pre>
28,獲取 iOS 路徑的方法
<pre>獲取家目錄路徑的函數
NSString *homeDir = NSHomeDirectory();
獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
獲取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();</pre>
29,字符串相關操作
<pre>去除所有的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]
去除首尾的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)uppercaseString; 全部字符轉為大寫字母
- (NSString *)lowercaseString 全部字符轉為小寫字母</pre>
30, CocoaPods pod install/pod update更新慢的問題
<pre>pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的參數,默認會升級CocoaPods的spec倉庫,加一個參數可以省略這一步,然后速度就會提升不少。</pre>
31,MRC和ARC混編設置方式
<pre>在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件
雙擊輸入 -fno-objc-arc 即可
MRC工程中也可以使用ARC的類,方法如下:
在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 即可</pre>
32,把tableview里cell的小對勾的顏色改成別的顏色
<pre>_mTableView.tintColor = [UIColor redColor];</pre>
33,調整tableview的separaLine線的位置
<pre>tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
</pre>
34,設置滑動的時候隱藏navigation bar
navigationController.hidesBarsOnSwipe = Yes
35,自動處理鍵盤事件,實現輸入框防遮擋的插件
IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager
36,Quartz2D相關
<pre>圖形上下是一個CGContextRef類型的數據。
圖形上下文包含:
1,繪圖路徑(各種各樣圖形)
2,繪圖狀態(顏色,線寬,樣式,旋轉,縮放,平移)
3,輸出目標(繪制到什么地方去?UIView、圖片)
1,獲取當前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
2,添加線條
CGContextMoveToPoint(ctx, 20, 20);
3,渲染
CGContextStrokePath(ctx);
CGContextFillPath(ctx);
4,關閉路徑
CGContextClosePath(ctx);
5,畫矩形
CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120));
6,設置線條顏色
[[UIColor redColor] setStroke];
7, 設置線條寬度
CGContextSetLineWidth(ctx, 20);
8,設置頭尾樣式
CGContextSetLineCap(ctx, kCGLineCapSquare);
9,設置轉折點樣式
CGContextSetLineJoin(ctx, kCGLineJoinBevel);
10,畫圓
CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100));
11,指定圓心
CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1);
12,獲取圖片上下文
UIGraphicsGetImageFromCurrentImageContext();
13,保存圖形上下文
CGContextSaveGState(ctx)
14,恢復圖形上下文
CGContextRestoreGState(ctx)</pre>
37,屏幕截圖
<pre> // 1. 開啟一個與圖片相關的圖形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);
// 2. 獲取當前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 3. 獲取需要截取的view的layer
[self.view.layer renderInContext:ctx];
// 4. 從當前上下文中獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 5. 關閉圖形上下文
UIGraphicsEndImageContext();
// 6. 把圖片保存到相冊
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);</pre>
37,左右抖動動畫
<pre>//1, 創建核心動畫
CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation];
//2, 告訴系統執行什么動畫。
keyAnima.keyPath = @"transform.rotation";
keyAnima.values = @[@(-M_PI_4 /90.0 * 5),@(M_PI_4 /90.0 * 5),@(-M_PI_4 /90.0 * 5)];
// 3, 執行完之后不刪除動畫
keyAnima.removedOnCompletion = NO;
// 4, 執行完之后保存最新的狀態
keyAnima.fillMode = kCAFillModeForwards;
// 5, 動畫執行時間
keyAnima.duration = 0.2;
// 6, 設置重復次數。
keyAnima.repeatCount = MAXFLOAT;
// 7, 添加核心動畫
[self.iconView.layer addAnimation:keyAnima forKey:nil];</pre>
38,CALayer 的知識
<pre>CALayer 負責視圖中顯示內容和動畫
UIView 負責監聽和響應事件
創建UIView對象時,UIView內部會自動創建一個圖層(既CALayer)
UIView本身不具備顯示的功能,是它內部的層才有顯示功能.
CALayer屬性:
position 中點(由anchorPoint決定)
anchorPoint 錨點
borderColor 邊框顏色
borderWidth 邊框寬度
cornerRadius 圓角半徑
shadowColor 陰影顏色
contents 內容
opacity 透明度
shadowOpacity 偏移
shadowRadius 陰影半徑
shadowColor 陰影顏色
masksToBounds 裁剪</pre>
39,性能相關
<pre>1. 視圖復用,比如UITableViewCell,UICollectionViewCell.
- 數據緩存,比如用SDWebImage實現圖片緩存。
- 任何情況下都不能堵塞主線程,把耗時操作盡量放到子線程。
- 如果有多個下載同時并發,可以控制并發數。
- 在合適的地方盡量使用懶加載。
- 重用重大開銷對象,比如:NSDateFormatter、NSCalendar。
- 選擇合適的數據存儲。
- 避免循環引用。避免delegate用retain、strong修飾,block可能導致循環引用,NSTimer也可能導致內存泄露等。
- 當涉及到定位的時候,不用的時候最好把定位服務關閉。因為定位耗電、流量。
- 加鎖對性能有重大開銷。
- 界面最好不要添加過多的subViews.
- TableView 如果不同行高,那么返回行高,最好做緩存。
- Viewdidload 里盡量不要做耗時操作。</pre>
40,驗證身份證號碼
<pre>//驗證身份證號碼
-
(BOOL)checkIdentityCardNo:(NSString)cardNo
{
if (cardNo.length != 18) {
return NO;
}
NSArray codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
int val;
BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
if (!isNum) {
return NO;
}
int sumValue = 0;for (int i =0; i
</pre>
41,響應者鏈條順序
<pre>1> 當應用程序啟動以后創建 UIApplication 對象
2> 然后啟動“消息循環”監聽所有的事件
3> 當用戶觸摸屏幕的時候, "消息循環"監聽到這個觸摸事件
4> "消息循環" 首先把監聽到的觸摸事件傳遞了 UIApplication 對象
5> UIApplication 對象再傳遞給 UIWindow 對象
6> UIWindow 對象再傳遞給 UIWindow 的根控制器(rootViewController)
7> 控制器再傳遞給控制器所管理的 view
8> 控制器所管理的 View 在其內部搜索看本次觸摸的點在哪個控件的范圍內(調用Hit test檢測是否在這個范圍內)
9> 找到某個控件以后(調用這個控件的 touchesXxx 方法), 再一次向上返回, 最終返回給"消息循環"
10> "消息循環"知道哪個按鈕被點擊后, 在搜索這個按鈕是否注冊了對應的事件, 如果注冊了, 那么就調用這個"事件處理"程序。(一般就是執行控制器中的"事件處理"方法)</pre>
42,使用函數式指針執行方法和忽略performSelector方法的時候警告
<pre>不帶參數的:
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);
帶參數的:
SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = func(_controller, selector, someRect, someView);
忽略警告:
pragma clang diagnostic push
pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[someController performSelector: NSSelectorFromString(@"someMethod")]
pragma clang diagnostic pop
如果需要忽視的警告有多處,可以定義一個宏:
define SuppressPerformSelectorLeakWarning(Stuff)
do {
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored "-Warc-performSelector-leaks"")
Stuff;
_Pragma("clang diagnostic pop")
} while (0)
使用方法:
SuppressPerformSelectorLeakWarning(
[_target performSelector:_action withObject:self]
);
</pre>
43,UIApplication的簡單使用
<pre>--------設置角標數字--------
//獲取UIApplication對象
UIApplication *ap = [UIApplication sharedApplication];
//在設置之前, 要注冊一個通知,從ios8之后,都要先注冊一個通知對象.才能夠接收到提醒.
UIUserNotificationSettings *notice =
[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
//注冊通知對象
[ap registerUserNotificationSettings:notice];
//設置提醒數字
ap.applicationIconBadgeNumber = 20;
--------設置聯網狀態--------
UIApplication *ap = [UIApplication sharedApplication];
ap.networkActivityIndicatorVisible = YES;</pre>