1 播放一張張連續(xù)的圖片,例如刷新動畫
/ 加入現(xiàn)在有三張圖片分別為animate_1、animate_2立哑、animate_3
// 方法一
imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];
imageView.animationDuration = 1.0;
// 方法二
imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
// 方法二解釋下夜惭,這個方法會加載animate_為前綴的,后邊0-1024铛绰,也就是animate_0诈茧、animate_1一直到animate_1024
2 tableView 使用總結(jié)
得到當前tableView顯示的 cell 數(shù)組
NSArray *cells = [self.tableView visibleCells];
// 判斷某一行的cell是否已經(jīng)顯示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
//tableView 自動滑動到某一行
//第一種方法
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//第二種方法
[self.tableVieW selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
3 讓導(dǎo)航控制器pop回指定的控制器
NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) {
if ([aViewController isKindOfClass:[RequiredViewController class]]) {
[self.navigationController popToViewController:aViewController animated:NO];
}
}
4 獲取屏幕方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if(orientation == 0) //Default orientation
//默認
else if(orientation == UIInterfaceOrientationPortrait)
//豎屏
else if(orientation == UIInterfaceOrientationLandscapeLeft)
// 左橫屏
else if(orientation == UIInterfaceOrientationLandscapeRight)
//右橫屏
5 監(jiān)聽scrollView是否滾動到了頂部/底部
-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
float scrollViewHeight = scrollView.frame.size.height;
float scrollContentSizeHeight = scrollView.contentSize.height;
float scrollOffset = scrollView.contentOffset.y;
if (scrollOffset == 0)
{
// 滾動到了頂部
}
else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
{
// 滾動到了底部
}
}
5 MD5加密
+ (NSString *)md5:(NSString *)str
{
const char *concat_str = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(concat_str, (unsigned int)strlen(concat_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i =0; i <16; i++){
[hash appendFormat:@"%02X", result[i]];
}
return [hash uppercaseString];
}
6 單個頁面多個網(wǎng)絡(luò)請求的情況,需要監(jiān)聽所有網(wǎng)絡(luò)請求結(jié)束后刷新UI
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t serialQueue = dispatch_queue_create("com.wzb.test.www", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 網(wǎng)絡(luò)請求一
[WebClick getDataSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *err) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 網(wǎng)絡(luò)請求二
[WebClick getDataSuccess:getBigTypeRM onSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 網(wǎng)絡(luò)請求三
[WebClick getDataSuccess:^{
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
// 所有網(wǎng)絡(luò)請求結(jié)束后會來到這個方法
dispatch_group_notify(group, serialQueue, ^{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// 刷新UI
});
});
});
//利用線程組
7 頁面跳轉(zhuǎn)實現(xiàn)翻轉(zhuǎn)動畫
// modal方式(模態(tài))
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];
vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:vc animated:YES completion:nil];
// push方式
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];
[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:0.80];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
[self.navigationController pushViewController:vc animated:YES];
[UIView commitAnimations];
8 獲取字符串中的數(shù)字
- (NSString *)getNumberFromStr:(NSString *)str
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
NSLog(@"%@", [self getNumberFromStr:@"12a0b05c1d2e3f4fda8fa8fad9fsad23"]);
// 12005123488923
}
9 某個界面多個事件同時響應(yīng)引起的問題, (比如點擊過快, push 了兩個頁面)
// 一個一個設(shè)置太麻煩了捂掰,可以全局設(shè)置
[[UIView appearance] setExclusiveTouch:YES];
// 或者只設(shè)置button
[[UIButton appearance] setExclusiveTouch:YES];
10 禁止手機睡眠
[UIApplication sharedApplication].idleTimerDisabled = YES;
11獲取app緩存大小
- (CGFloat)getCachSize {
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
//獲取自定義緩存大小
//用枚舉器遍歷 一個文件夾的內(nèi)容
//1.獲取 文件夾枚舉器
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
__block NSUInteger count = 0;
//2.遍歷
for (NSString *fileName in enumerator) {
NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
count += fileDict.fileSize;//自定義所有緩存大小
}
// 得到是字節(jié) 轉(zhuǎn)化為M
CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
return totalSize;
}
12 清理app緩存
- (void)handleClearView {
//刪除兩部分
//1.刪除 sd 圖片緩存
//先清除內(nèi)存中的圖片緩存
[[SDImageCache sharedImageCache] clearMemory];
//清除磁盤的緩存
[[SDImageCache sharedImageCache] clearDisk];
//2.刪除自己緩存
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
[[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}
13 AFNetworking監(jiān)聽網(wǎng)絡(luò)狀態(tài)
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
break;
case AFNetworkReachabilityStatusNotReachable: {
[SVProgressHUD showInfoWithStatus:@"當前設(shè)備無網(wǎng)絡(luò)"];
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[SVProgressHUD showInfoWithStatus:@"當前Wi-Fi網(wǎng)絡(luò)"];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
[SVProgressHUD showInfoWithStatus:@"當前蜂窩移動網(wǎng)絡(luò)"];
break;
default:
break;
}
}];
14 獲取一個視頻的第一幀圖片
NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return one;
15 獲取視頻的時長
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
NSURL *videoUrl = [NSURL URLWithString:urlString];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);
return seconds;
}
16 刪除NSUserDefaults所有記錄
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
17 為UIView某個角添加圓角
// 左上角和右下角添加圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
18 將一個view放置在其兄弟視圖的最上面
[parentView bringSubviewToFront:yourView]
// 將一個view放置在其兄弟視圖的最下面
[parentView sendSubviewToBack:yourView]
19 讓手機震動一下
導(dǎo)入框架
#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
20 在非ViewController的地方彈出UIAlertController對話框
// 最好抽成一個分類
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
//...
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertController animated:YES completion:nil];
21 在狀態(tài)欄增加網(wǎng)絡(luò)請求的菊花敢会,類似safari加載網(wǎng)頁的時候狀態(tài)欄菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
22 將一個image保存在相冊中
import <Photos/Photos.h>
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
changeRequest.creationDate = [NSDate date];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"successfully saved");
}
else {
NSLog(@"error saving to photos: %@", error);
}
}];