iOS 開發常用的知識點匯總

1.NSString過濾特殊字符串
定義一個特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-+=\|~<>$€?'@#$%&*()+'""];

過濾字符串的特殊字符
NSString *newString = [NSString stringByTrimmingCharactersInSet:set];

2.TransForm屬性
平移
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;

3.計算方法耗時時間間隔
獲取時間間隔

define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

4.Alert提示宏定義

define Alert(S, …) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(S), ##VA_ARGS] delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil] show]

5.讓iOS應用直接退出

  • (void)exitApplication {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    [UIView animateWithDuration:1.0f animations:^{
    window.alpha = 0;
    } completion:^(BOOL finished) {
    exit(0);
    }];
    }

6.快速求總和 最大值 最小值 和 平均值
NSArray 快速求總和 最大值 最小值 和 平均值
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(@"%f\n%f\n%f\n%f",sum,avg,max,min);

7.修改Label中不同文字顏色

  • (void)touchesEnded:(NSSet<UITouch> *)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;
    }

8.Label行間距
-(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;

}

9.UIImageView填充模式
@"UIViewContentModeScaleToFill", // 拉伸自適應填滿整個視圖
@"UIViewContentModeScaleAspectFit", // 自適應比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下

10.iOS開發中一些相關的路徑
//模擬器的位置:
/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

//獲取 iOS 路徑的方法
//獲取家目錄路徑的函數
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();

11.關于隱藏Navigation bar
/*
//設置滑動的時候隱藏Navigation bar
navigationController.hidesBarsOnSwipe = Yes
//動態隱藏NavigationBar
*/

1當我們的手離開屏幕時候隱藏

  • (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
    {
    if(velocity.y > 0)
    {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    } else {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    }
    PS: velocity.y這個量,在上滑和下滑時,變化極小(小數),但是因為方向不同,有正負之分,這就很好處理了

2.在滑動過程中隱藏
(1) self.navigationController.hidesBarsOnSwipe = YES;
(2) 滑動試圖的代理方法

  • (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
    CGFloat offsetY = scrollView.contentOffset.y + __tableView.contentInset.top;
    CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y;
    if (offsetY > 64) {
    if (panTranslationY > 0)
    {
    //下滑趨勢,顯示
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    } else {
    //上滑趨勢,隱藏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    } else {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    }
    PS: 這里的offsetY > 64只是為了在視圖滑過navigationBar的高度之后才開始處理,防止影響展示效果。panTranslationY是scrollView的pan手勢的手指位置的y值,可能不是太好,因為panTranslationY這個值在較小幅度上下滑動時,可能都為正或都為負,這就使得這一方式不太靈敏.

12.自動處理鍵盤事件,實現輸入框防遮擋的插件
https://github.com/hackiftekhar/IQKeyboardManager

13.設置字體和行間距
1 設置字體和行間距
UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)];
lable.text = @"大家好,我是奮拓達,在這里我們一起學習新的知識,總結我們遇到的那些坑,共同的學習,共同的進步,共同的努力,只為美好的明天!!!有問題一起相互的探討—123456!!!";
lable.numberOfLines = 0;
lable.font = [UIFont systemFontOfSize:12];
lable.backgroundColor = [UIColor grayColor];
[self.view addSubview:lable];

2 設置每個字體之間的間距
NSKernAttributeName 這個對象所對應的值是一個NSNumber對象(包含小數),作用是修改默認字體之間的距離調整,值為0的話表示字距調整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];

3 設置某寫字體的顏色
NSForegroundColorAttributeName 設置字體顏色
NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"xiao公子"].location, [[str string] rangeOfString:@"Frank_chun"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange];
NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"123456"].location, [[str string] rangeOfString:@"438637472"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];

****4 設置每行之間的間距****
NSParagraphStyleAttributeName 設置段落的樣式
NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init];
[par setLineSpacing:20];

*****5 為某一范圍內文字添加某個屬性*****
NSMakeRange表示所要的范圍,從0到整個文本的長度
[str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];

14.點擊button倒計時
1第一種方法
// 點擊button倒計時

import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIButton * timeButton;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong)UIButton * btn;
@end@implementation ViewController
{
NSInteger _time;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    _time = 5;
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom]; _btn.backgroundColor = [UIColor orangeColor];
    [_btn setTitle:@"獲取驗證碼" forState:UIControlStateNormal]; _btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self refreshButtonWidth];
    [self.view addSubview:self.btn];
    }
  • (void)refreshButtonWidth{
    CGFloat width = 0;
    if (_btn.enabled){
    width = 100;
    } else {
    width = 200;
    }
    _btn.center = CGPointMake(self.view.frame.size.width/2, 200);
    _btn.bounds = CGRectMake(0, 0, width, 40);
    //每次刷新,保證區域正確
    [_btn setBackgroundImage:[self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];
    [_btn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled];
    }
  • (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize{
    CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height); UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
    return image;
    }
  • (void)btnAction:(UIButton *)sender{
    sender.enabled = NO;
    [self refreshButtonWidth];
    [sender setTitle:[NSString stringWithFormat:@"獲取驗證碼(%zi)", _time] forState:UIControlStateNormal];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
    }
  • (void)timeDown{
    _time —;
    if (_time == 0) {
    [_btn setTitle:@"重新獲取" forState:UIControlStateNormal]; _btn.enabled = YES;
    [self refreshButtonWidth];
    [_timer invalidate];
    _timer = nil;
    _time = 5 ;
    return;
    }
    [_btn setTitle:[NSString stringWithFormat:@"獲取驗證碼(%zi)", _time] forState:UIControlStateNormal];
    }

2 第二種方法
// 點擊發送驗證碼

  • (void)sendMessage:(UIButton )btn{
    if (self.phoneField.text.length == 0) {
    [self remindMessage:@"請輸入正確的手機號"];
    }else{
    __block int timeout=60;
    //倒計時時間
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0
    NSEC_PER_SEC, 0);
    //每秒執行
    dispatch_source_set_event_handler(_timer, ^{
    if(timeout<=0){
    //倒計時結束,關閉
    dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{
    // 設置界面的按鈕顯示 根據自己需求設置
    [btn setTitle:@"發送驗證碼" forState:UIControlStateNormal]; btn.userInteractionEnabled = YES;
    });
    }else{
    int seconds = timeout % 60;
    NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
    if ([strTime isEqualToString:@"0"]) {
    strTime = [NSString stringWithFormat:@"%d",60];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
    //設置界面的按鈕顯示 根據自己需求設置
    //NSLog(@"____%@",strTime);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    [btn setTitle:[NSString stringWithFormat:@"%@秒后重新發送",strTime] forState:UIControlStateNormal];
    [UIView commitAnimations];
    btn.userInteractionEnabled = NO;
    });
    timeout—;
    }
    });
    dispatch_resume(_timer);
    }

15.修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"username is in here!"; [/p][textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

16.圖片拉伸
UIImage* img=[UIImage imageNamed:@"2.png"];//原圖
UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10);
UIImageResizingModeStretch:拉伸模式,通過拉伸UIEdgeInsets指定的矩形區域來填充圖片
UIImageResizingModeTile:平鋪模式,通過重復顯示UIEdgeInsets指定的矩形區域來填充圖
img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch];
self.imageView.image=img;

17.去掉導航欄下邊的黑線
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

18.修改pagecontrol顏色
_pageControl.currentPageIndicatorTintColor=SFQRedColor;
_pageControl.pageIndicatorTintColor=SFQGrayColor;

19.去掉UITableView的section的粘性,使其不會懸停
//有時候使用UITableView所實現的列表,會使用到section,但是又不希望它粘在最頂上而是跟隨滾動而消失或者出現
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == _tableView) {
CGFloat sectionHeaderHeight = 36;
if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}

20.UIImage與字符串互轉
1 圖片轉字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image
{
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return encodedImageStr;
}

2 字符串轉圖片
-(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
return _decodedImage;
}

21.判斷NSString中是否包含中文
-(BOOL)isChinese:(NSString *)str{
NSString *match=@"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:str];
}

22.NSDate與NSString的相互轉化
-(NSString *)dateToString:(NSDate *)date {
// 初始化時間格式控制器
NSDateFormatter *matter = [[NSDateFormatter alloc] init];
// 設置設計格式
[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
// 進行轉換
NSString *dateStr = [matter stringFromDate:date];
return dateStr;
}
-(NSDate *)stringToDate:(NSString *)dateStr {

    // 初始化時間格式控制器
    NSDateFormatter *matter = [[NSDateFormatter alloc] init];
    // 設置設計格式
    [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
    // 進行轉換
    NSDate *date = [matter dateFromString:dateStr];
    return date;
}

23.控件的局部圓角
CGRect rect = CGRectMake(0, 0, 100, 50);
CGSize radio = CGSizeMake(5, 5);//圓角尺寸
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//這只圓角位置
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//創建shapelayer
masklayer.frame = button.bounds;
masklayer.path = path.CGPath;//設置路徑
button.layer.mask = mask layer;

24.NavigationBar的透明問題
(1) 如果僅僅是想要navigationBar透明,按鈕和標題都在可以使用以下方法:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//給navigationBar設置一個空的背景圖片即可實現透明,而且標題按鈕都在

PS: 如果僅僅把navigationBar的alpha設為0的話,那就相當于把navigationBar給隱藏了,大家都知道,父視圖的alpha設置為0的話,那么子視圖全都會透明的。那么相應的navigationBar的標題和左右兩個按鈕都會消失。這樣顯然達不到我們要求的效果。

(2)如果你想在透明的基礎上實現根據下拉距離,由透明變得不透明的效果,那么上面那個就顯得力不從心了,這就需要我們采用另外一種方法了
//Navigation Bar是一個復合視圖,它是有許多個控件組成的,那么我們就可以從他的內部入手
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;//這里可以根據scrollView的偏移量來設置alpha就實現了漸變透明的效果

25.全局設置Navigation Bar標題的樣式和barItem的標題樣式
//UIColorWithHexRGB( )這個方法是自己定義的,這里只需要給個顏色就好了
[[UINavigationBar appearance] setBarTintColor:UIColorWithHexRGB(0xfefefe)];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:UIColorWithHexRGB(0xfe6d27)}];
[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName : UIColorWithHexRGB(0x666666)} forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize];

26.側滑手勢返回
iOS的側滑返回手勢有著很好的操作體驗,不支持側滑返回的應用絕對不是好應用。但是在開發過程中在自定義了返回按鈕,或者某些webView,tableView等頁面,側滑返回手勢失效,這時候就需要我們來進行設置一下了,可以在基類里面協商如下代碼:

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//需要遵循一下手勢的代理 self.navigationController.interactivePopGestureRecognizer.delegate = self;
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

問題:當返回navigationController的最頂層的Controller的時候。再次側滑,這個時候你在點擊一個push頁面的操作,你會發現卡那了,半天才會有反應。
解釋 :這是由于,在最頂層Controller手勢依然有效,但是滑動后,并找不到返回的頁面。造成軟件卡頓,假死所以就要在rootViewController中讓此手勢失效。把下面的設為NO
self.navigationController.interactivePopGestureRecognizer.enabled = YES;

PS :當然你也可以使用一個第三方庫,寫的相當棒。他對系統的側滑返回手勢進行拓展,不用從邊緣滑動,只要右滑即可返回。最重要的是,他只需要加入項目中即可,不需要一行代碼即可實現。附上github 網址
https://github.com/forkingdog/FDFullscreenPopGesture

27.給webView添加頭視圖
webView是一個復合視圖,里面包含有一個scrollView,scrollView里面是一個UIWebBrowserView(負責顯示WebView的內容)
UIView webBrowserView = self.webView.scrollView.subviews[0];//拿到webView的webBrowserView
self.backHeadImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth
2/3.0)];
[_backHeadImageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
[self.webView insertSubview:_backHeadImageView belowSubview:self.webView.scrollView];
//把backHeadImageView插入到webView的scrollView下面
CGRect frame = self.webBrowserView.frame;
frame.origin.y = CGRectGetMaxY(_backHeadImageView.frame);
self.webBrowserView.frame = frame;
//更改webBrowserView的frame向下移backHeadImageView的高度,使其可見

28.模態跳轉的動畫設置 Model
DetailViewController *detailVC = [[DetailViewController alloc]init];

UIModalTransitionStyleFlipHorizontal  翻轉
UIModalTransitionStyleCoverVertical   底部滑出
UIModalTransitionStyleCrossDissolve  漸顯
UIModalTransitionStylePartialCurl        翻頁
                                                    
detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
[self presentViewController:detailVC animated:YES completion:nil];

29.圖片處理只拿到圖片的一部分
UIImage *image = [UIImage imageNamed:filename];
CGImageRef imageRef = image.CGImage;
CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);
//這里的寬高是相對于圖片的真實大小
//比如你的圖片是400x400的那么(0,0,400,400)就是圖片的全尺寸,想取哪一部分就設置相應坐標即可
CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

30.給UIView設置圖片
UIImage *image = [UIImage imageNamed:@"playing"];
_layerView.layer.contents = (__bridge id)image.CGImage;
_layerView.layer.contentsCenter = CGRectMake(0.25, 0.25, 0.5, 0.5);
//同樣可以設置顯示的圖片范圍
//不過此處略有不同,這里的四個值均為0-1之間;對應的依然是寫x,y,widt,height

31.給TableView或者CollectionView的cell添加簡單動畫 (只要在willDisplayCell方法中對將要顯示的cell做動畫即可)

  • (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = tableView.indexPathsForVisibleRows;
    NSIndexPath *firstIndexPath = array[0];
    //設置anchorPoint
    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    //為了防止cell視圖移動,重新把cell放回原來的位置
    cell.layer.position = CGPointMake(0, cell.layer.position.y);
    //設置cell 按照z軸旋轉90度,注意是弧度
    if (firstIndexPath.row < indexPath.row) {
    cell.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1.0);
    }else{
    cell.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 0, 1.0);
    }
    cell.alpha = 0.0;
    [UIView animateWithDuration:1 animations:^{
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1.0;
    }];
    }

32.兩點之間的距離 & 線程中更新UILabel的text
1 兩點之間的距離
static__inline__ CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2) {
CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y;
returnsqrt(dxdx + dydy);

}

2 線程中更新UILabel的text

abel1為UILabel,當在子線程中,需要進行text的更新的時候,可以使用這個方法來更新。
其他的UIView也都是一樣的。
[self.label1 performSelectorOnMainThread:@selector(setText:) withObject:textDisplay waitUntilDone:YES];

33.獲得當前硬盤空間
NSFileManagerfm = [NSFileManagerdefaultManager];
NSDictionary
fattributes = [fmattributesOfFileSystemForPath:NSHomeDirectory()error:nil];
NSLog(@"容量%lldG",[[fattributesobjectForKey:NSFileSystemSize]longLongValue]/1000000000);
NSLog(@"可用%lldG",[[fattributesobjectForKey:NSFileSystemFreeSize]longLongValue]/1000000000);

34.ActivityViewController使用AirDrop分享
使用AirDrop進行分享:
NSArray array =@[@"test1",@"test2"];
UIActivityViewController
activityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];
[selfpresentViewController:activityVCanimated:YES
completion:^{
NSLog(@"Air");

}];

35.保存全屏為image
CGSizeimageSize = [[UIScreenmainScreen]bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize,NO,0);
CGContextRefcontext =UIGraphicsGetCurrentContext();
for(UIWindow* windowin[[UIApplicationsharedApplication]windows]) {
if(![windowrespondsToSelector:@selector(screen)] || [windowscreen] == [UIScreenmainScreen]) {
CGContextSaveGState(context);
CGContextTranslateCTM(context, [windowcenter].x, [windowcenter].y);
CGContextConcatCTM(context, [windowtransform]);
CGContextTranslateCTM ( context, -[windowbounds].size.width *[[windowlayer]anchorPoint].x, -[windowbounds].size.height [[windowlayer]anchorPoint].y);
[[windowlayer]renderInContext:context];
CGContextRestoreGState(context);
}
}
UIImage
image = UIGraphicsGetImageFromCurrentImageContext();

36.獲取通訊錄聯系人的電話號碼

import

import

ABPeoplePickerNavigationControllerDelegate

  • (void)addAddress {
    RYLog(@"選擇聯系人");
    ABPeoplePickerNavigationController * vc =[[ABPeoplePickerNavigationController alloc] init];
    vc.peoplePickerDelegate =self;
    [selfpresentViewController:vc animated:YEScompletion:nil];
    }

pragma mark -- ABPeoplePickerNavigationControllerDelegate

  • (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);

//電話號碼

CFStringRef telValue = ABMultiValueCopyValueAtIndex(valuesRef,index);
[selfdismissViewControllerAnimated:YEScompletion:^{
self.addressV.telnum.text = (__bridgeNSString *)telValue;

}];

}

37.用WebView加載頁面,提前獲取頁面的高度
可以獲得內容高度,但是網絡不好時,不準確
1.webView.scrollView.contentSize.height;
獲取的高度較為準確
2.[[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue]

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,316評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,481評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,241評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,939評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,697評論 6 409
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,182評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,247評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,406評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,933評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,772評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,973評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,516評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,638評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,866評論 1 285
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,644評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,953評論 2 373

推薦閱讀更多精彩內容

  • *7月8日上午 N:Block :跟一個函數塊差不多,會對里面所有的內容的引用計數+1,想要解決就用__block...
    炙冰閱讀 2,511評論 1 14
  • 1. 打印View所有子視圖 po [[self view]recursiveDescription] 2. la...
    Hurricane_4283閱讀 980評論 0 2
  • 打印View所有子視圖 layoutSubviews調用的調用時機 當視圖第一次顯示的時候會被調用當這個視圖顯示到...
    hyeeyh閱讀 521評論 0 3
  • 每一次的快門,都是全新的世界。 你的瀏覽,就是我的動力。 希望能關注“攝影人”專題,謝謝。
    技能Mrboy閱讀 272評論 0 4
  • 作者:石力豪 東馬路小學 四年級 指導老師:底婷 雪飛風寒百花謝, 梅在枝頭紅似火。 手捧雪花白如云, 忽然之間化...
    墨點無多閱讀 388評論 0 0