iOS 知識-經常使用小技巧大雜燴

1. 打印View全部子視圖

po [[self view]recursiveDescription]

2. layoutSubviews調用的調用時機

* 當視圖第一次顯示的時候會被調用
* 當這個視圖顯示到屏幕上了,點擊按鈕
* 添加子視圖也會調用這個方法
* 當本視圖的大小發生改變的時候是會調用的
* 當子視圖的frame發生改變的時候是會調用的
* 當刪除子視圖的時候是會調用的

3. NSString過濾特殊字符

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

4. 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;

5. 去掉分割線多餘15像素

首先在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];    
    }
}

6. 計算方法耗時時間間隔

// 獲取時間間隔
#define TICK   CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define TOCK   NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

7. Color顏色宏定義

// 隨機顏色
#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)]

8. Alert提示宏定義

#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil] show]

9. 讓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);
    }];
}

10. 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);

10. 修改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;
}

11. 播放聲音

#import<AVFoundation>
   //  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];

12. 檢測是否IPad Pro

- (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) < DBL xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed>> ~/.lldbinit
    echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
下次從新運行項目,而後就不報錯了。

25. 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;
}

26. UIImageView填充模式

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

27. 宏定義檢測block是否可用

#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };   
// 宏定義以前的用法
 if (completionBlock)   {   
    completionBlock(arg1, arg2); 
  }    
// 宏定義以後的用法
 BLOCK_EXEC(completionBlock, arg1, arg2);

28. Debug欄打印時自動把Unicode編碼轉化成漢字

// 有時候咱們在xcode中打印中文,會打印出Unicode編碼,還須要本身去一些在線網站轉換,有了插件就方便多了。
 DXXcodeConsoleUnicodePlugin 插件

29. 設置狀態欄文字樣式顏色

[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

30. 自動生成模型代碼的插件

// 可自動生成模型的代碼,省去寫模型代碼的時間
ESJsonFormat-for-Xcode

31. iOS中的一些手勢

輕擊手勢(TapGestureRecognizer)
輕掃手勢(SwipeGestureRecognizer)
長按手勢(LongPressGestureRecognizer)
拖動手勢(PanGestureRecognizer)
捏合手勢(PinchGestureRecognizer)
旋轉手勢(RotationGestureRecognizer)

32. 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

33. 獲取 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();

34. 字符串相關操做

去除全部的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]

去除首尾的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

- (NSString *)uppercaseString; 所有字符轉爲大寫字母
- (NSString *)lowercaseString 所有字符轉爲小寫字母

35. CocoaPods pod install/pod update更新慢的問題

pod install --verbose --no-repo-update 
pod update --verbose --no-repo-update
若是不加後面的參數,默認會升級CocoaPods的spec倉庫,加一個參數能夠省略這一步,而後速度就會提高很多。

36. MRC和ARC混編設置方式

在XCode中targets的build phases選項下Compile Sources下選擇 不須要arc編譯的文件
雙擊輸入 -fno-objc-arc 便可

MRC工程中也可使用ARC的類,方法以下:
在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 便可

37. 把tableview裏cell的小對勾的顏色改爲別的顏色

_mTableView.tintColor = [UIColor redColor];

38. 調整tableview的separaLine線的位置

tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

39. 設置滑動的時候隱藏navigationbar

navigationController.hidesBarsOnSwipe = Yes

40. 自動處理鍵盤事件,實現輸入框防遮擋的插件

IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager

41. Quartz2D相關

圖形上下是一個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)

42. 屏幕截圖

// 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);

第二種寫法javascript

/**
     *截圖功能
     */
     -(void)screenShot{
         
         
         CGRect rect = self.view.frame;
         UIGraphicsBeginImageContext(rect.size);
         CGContextRef context = UIGraphicsGetCurrentContext();
         [self.view.layer renderInContext:context];
         UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
         
         i = [[UIImageView alloc]initWithFrame:CGRectMake(20, 70, 300, 500)];
         i.layer.borderColor = [UIColor redColor].CGColor;
         i.layer.borderWidth = 2;
         i.image = img;
         
         [self.view addSubview:i];
         i.userInteractionEnabled = YES;
         //tap手勢
         UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(event:)];
         [i addGestureRecognizer:tapGesture];
         [tapGesture setNumberOfTapsRequired:1];
         
     }

43. 隱藏導航欄上的返回字體

//Swift
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)
//OC
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

44. 解決tableview的分割線短一截

-(void)viewDidLayoutSubviews{
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{ 
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) 
{
[self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; 
}
}
-(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]; 
}
}

45. 動態隱藏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]; 
}
}
velocity.y這個量,在上滑和下滑時,變化極小(小數),可是由於方向不一樣,有正負之分,這就很好處理了。
//2.在滑動過程當中隱藏
//像safari
(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]; 
}
}
這裏的offsetY > 64只是爲了在視圖滑過navigationBar的高度以後纔開始處理,防止影響展現效果。panTranslationY是scrollView的pan手勢的手指位置的y值,可能不是太好,由於panTranslationY這個值在較小幅度上下滑動時,可能都爲正或都爲負,這就使得這一方式不太靈敏.

效果圖php

46. 設置導航欄透明

1第一種方式css

//方法一:設置透明度
[[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1];
//方法二:設置背景圖片
/**
 * 設置導航欄,使其透明
 *
*/
- (void)setNavigationBarColor:(UIColor *)color targetController:(UIViewController *)targetViewController{
//導航條的顏色 以及隱藏導航條的顏色targetViewController.navigationController.navigationBar.shadowImage = [[UIImage alloc]init]; 
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); 
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [targetViewController.navigationController.navigationBar setBackgroundImage:theImage forBarMetrics:UIBarMetricsDefault];
}

二、設置透明導航欄html

當即投資BG爲默認的導航欄 背景圖片  java

透明navbarBG 是一張純透明的png 圖片python

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self createNav];
  
}
- (void)createNav
{
    //替換導航欄透明
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    [navigationBar setTitleTextAttributes:@{
                                            NSForegroundColorAttributeName :[UIColor whiteColor]
                                            }];
    //navigationBar.alpha = 0;
    [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsDefault];
    [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsCompact];
    //去黑線
    [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage new]];
}
//退出頁面時候 恢復不透明
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"當即投資BG"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"當即投資BG"] forBarMetrics:UIBarMetricsCompact];
   }
// 當滾動視圖滾動到最頂端後,執行該方法 
//向上滾動時候不透明
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    // NSLog(@"scrollViewDidScroll");
    
    CGPoint point=scrollView.contentOffset;
    if(point.y>5){
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"當即投資BG"] forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"當即投資BG"] forBarMetrics:UIBarMetricsCompact];
        self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:243/255.0 green:90.0/255.0 blue:3.0/255.0 alpha:1.0];
    }else{
        UINavigationBar *navigationBar = self.navigationController.navigationBar;
        [navigationBar setTitleTextAttributes:@{
                                                NSForegroundColorAttributeName :[UIColor whiteColor]
                                                }];
        //navigationBar.alpha = 0;
        [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsDefault];
        [navigationBar setBackgroundImage:[UIImage imageNamed:@"透明navbarBG"] forBarMetrics:UIBarMetricsCompact];
    }
    // NSLog(@"%f,%f",point.x,point.y);
    // 從中能夠讀取contentOffset屬性以肯定其滾動到的位置。
    // 注意:當ContentSize屬性小於Frame時,將不會出發滾動
}

47. 設置字體和行間距

//設置字體和行間距 
UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)]; 
lable.text = @"你們好,我是Frank_chun,在這裏咱們一塊兒學習新的知識,總結咱們遇到的那些坑,共同的學習,共同的進步,共同的努力,只爲美好的明天!!!有問題一塊兒相互的探討--438637472!!!"; 
lable.numberOfLines = 0;
lable.font = [UIFont systemFontOfSize:12];
lable.backgroundColor = [UIColor grayColor]; 
[self.view addSubview:lable]; 
//設置每一個字體之間的間距 
//NSKernAttributeName 這個對象所對應的值是一個NSNumber對象(包含小數),做用是修改默認字體之間的距離調整,值爲0的話表示字距調整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];
//設置某寫字體的顏色
//NSForegroundColorAttributeName 設置字體顏色
NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length); 
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange]; 
NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];
//設置每行之間的間距 
//NSParagraphStyleAttributeName 設置段落的樣式
NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init];
[par setLineSpacing:20];
//爲某一範圍內文字添加某個屬性
//NSMakeRange表示所要的範圍,從0到整個文本的長度
[str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];

效果圖git

48. 點擊button倒計時

//第一種方法
//點擊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];
}
//第二種方法
#pragma mark -點擊發送驗證碼
- (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);
}

效果圖github

49. UITextField默認佔位符是居中顯示,讓其居上顯示

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

50. 解決同時按兩個按鈕進兩個view的問題

[button setExclusiveTouch:YES];

51. 圖片拉伸

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;

52. 修改textFieldplaceholder字體顏色和大小

textField.placeholder = @"username is in here!";  
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

53. 修改狀態欄字體顏色

只能設置兩種顏色,黑色和白色,系統默認黑色
設置爲白色方法:
(1)在plist裏面添加Status bar style,值爲UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)
(2)在Info.plist中設置UIViewControllerBasedStatusBarAppearance 爲NO

54. 去掉導航欄下邊的黑線

[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

55. 修改pagecontrol顏色

_pageControl.currentPageIndicatorTintColor=SFQRedColor;
_pageControl.pageIndicatorTintColor=SFQGrayColor;

56. 去掉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);  
        }  
    }  
}

57. 經過2D仿射函數實現小的動畫效果(變大縮小) --可用於自定義pageControl中

[UIView animateWithDuration:0.3 animations:^{
       imageView.transform = CGAffineTransformMakeScale(2, 2);
       } completion:^(BOOL finished) {
       imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
       }];

58. UIImage與字符串互轉

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

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

59. 判斷NSString中是否包含中文

-(BOOL)isChinese:(NSString *)str{
    NSString *match=@"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

60. 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;
}

6一、imageView添加手勢

imageview.userInteractionEnabled = YES;
     //tap手勢
     UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(event:)];
     [imageview addGestureRecognizer:tapGesture];
    [tapGesture setNumberOfTapsRequired:1];

    - (void)event:(UITapGestureRecognizer *)gesture
    {
        NSLog(@"單擊");
    }

6二、獲取請求鏈接裏邊的cookies

#pragma mark //獲取請求鏈接的cookies
     
 [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    if (success) {
        success(responseObject);
        
        NSDictionary *fields = [operation.response allHeaderFields]; //afnetworking寫法
        NSLog(@"fields = %@",[fields description]);
        // NSURL *url = [NSURL URLWithString:@"http://api.skyfox.org/api-test.php"];
        NSURL *url = [NSURL URLWithString:urlStr];
        //獲取cookie方法1
        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url];
        NSLog(@"11--%@",cookies);
        //獲取cookie方法2
        //NSString *cookieString = [[HTTPResponse allHeaderFields] valueForKey:@"Set-Cookie"];
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //  NSLog(@"%@", error);
    if (fail) {
        fail();
    }
}];

63圖片旋轉

imageView1 .transform=CGAffineTransformMakeRotation(M_PI_2);

6四、獲取字符串在label中須要的寬度

#pragma mark //獲取字符串須要的寬度
 +(CGFloat)ZFYtextWidthFromTextString:(NSString *)text fontSize:(CGFloat)size{
     
     CGSize size1 = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:size]}];    //返回計算出的行高
     return size1.width;
 }

6五、獲取字符串在label中須要的高度

#pragma mark//獲取字符串須要的高度
 +(CGFloat)ZFYtextHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{
     
     NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
     CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
     //返回計算出的行高
     return rect.size.height;
 }

6六、漢字和Unicode編碼轉換

#pragma mark//Unicode轉漢字   \u5f20\u4e09 → 張三
 - (NSString *)replaceUnicode:(NSString *)unicodeStr {
     //張三  \u5f20\u4e09
     
     NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
     NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
     NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
     NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
     NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                            mutabilityOption:NSPropertyListImmutable
                                                                      format:NULL
                                                            errorDescription:NULL];
     
     //  NSLog(@"Output = %@", returnStr);
     return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
 }
#pragma mark//漢字轉 Unicode   張三 →  \u5f20\u4e09
 -(NSString *) utf8ToUnicode:(NSString *)string{
     
     NSUInteger length = [string length];
     NSMutableString *s = [NSMutableString stringWithCapacity:0];
     for (int i = 0;i < length; i++){
         unichar _char = [string characterAtIndex:i];
         //判斷是否爲英文和數字
         if (_char <= '9' && _char >='0'){
             [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
         }else if(_char >='a' && _char <= 'z'){
             [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
         }else if(_char >='A' && _char <= 'Z')
         {
             [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
         }else{
             [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
         }
     }
     return s;
 }

6七、獲取間隔一天 一年一秒以後的時間

#pragma mark //獲取相對時間  獲取兩個月前的時間  -2 爲兩個月前時間   2爲兩個月後時間
 - (void)RelativeTime {
     NSDateComponents * components = [[NSDateComponents alloc] init];
     components.month = -2;
     //    components.day = 10;
     //    components.hour = 10;
     NSCalendar * calendar = [NSCalendar currentCalendar];
     
     NSDate * currentDate = [NSDate date];
     NSDate * nextData = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
     NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
     
     formatter.dateFormat = @"yyyy年MM月dd日HH時mm分ss秒";
     NSString * str = [formatter stringFromDate:nextData];
     NSLog(@"%@",str);
     
 }

6八、打印系統字體庫名字

#pragma mark   打印系統字體庫 名字
 NSArray *familyNames = [UIFont familyNames];
 for( NSString *familyName in familyNames )
 {
     printf( "Family: %s \n", [familyName UTF8String]);
     
     NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
     for( NSString *fontName in fontNames )
     {
         printf( "\tFont: %s \n", [fontName UTF8String] );
         
     }
 }

6九、 截取正方形的圖片

//截取正方形的圖片 centerBool爲YES  表示從中心開始截取
+(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool{
 /*如若centerBool爲Yes則是由中心點取mCGRect範圍的圖片*/
 
 float imgWidth = image.size.width;
 float imgHeight = image.size.height;
 float viewWidth = mCGRect.size.width;
 float viewHidth = mCGRect.size.height;
 CGRect rect;
 if(centerBool)
     rect = CGRectMake((imgWidth-viewWidth)/2,(imgHeight-viewHidth)/2,viewWidth,viewHidth);
 else{
     if(viewHidth<viewWidth)
     {
         if(imgWidth<= imgHeight)
         {
             rect=CGRectMake(0, 0,imgWidth, imgWidth*viewHidth/viewWidth);
         }else
         {
             float width = viewWidth*imgHeight/viewHidth;
             float x = (imgWidth  - width)/2;
             if(x>0)
             {
                 rect = CGRectMake(x,0,  width, imgHeight);
             }else
             {
                 rect =  CGRectMake(0,  0,  imgWidth, imgWidth*viewHidth/viewWidth);
             }
         }
     }else
     {
         if(imgWidth <= imgHeight)
         {
             float height = viewHidth*imgWidth/viewWidth;
             if(height< imgHeight)
             {
                 rect =CGRectMake(0,  0, imgWidth, height);
             }else
             {
                 rect = CGRectMake(0,  0,viewWidth*imgHeight/viewHidth, imgHeight);
             }
         }else
         {
             float width = viewWidth*imgHeight/viewHidth;
             if(width< imgWidth)
             {
                 float x =  (imgWidth - width)/2;
                 rect =CGRectMake(x,  0,width, imgHeight);
             }else
             {
                 rect =CGRectMake(0,  0,imgWidth, imgHeight);
             }
         }
     }
 }
 
 CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage,rect);
 CGRect smallBounds =CGRectMake(0, 0,CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
 
 UIGraphicsBeginImageContext(smallBounds.size); CGContextRef context =UIGraphicsGetCurrentContext();CGContextDrawImage(context, smallBounds, subImageRef);
 UIImage *smallImage =[UIImage imageWithCGImage:subImageRef];
 UIGraphicsEndImageContext();
 
 return smallImage;
}

70、跳轉APPstore

//APPid就是上面的那串數字

NSString  *urlStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",APPID];
NSURL *url = [NSURLURLWithString:urlStr];

[[UIApplicationsharedApplication]openURL:url];

7一、 獲取本機APP 版本號

#pragma mark --  //獲取本地版本號
     //獲取本地版本號
     NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

7二、獲取APP store 項目版本號

#pragma mark -- 獲取appstore版本號
-(void)Postpath:(NSString *)path
{
NSString *url = [[NSString alloc] initWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"414478124"];
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:10];

[request setHTTPMethod:@"POST"];


NSOperationQueue *queue = [NSOperationQueue new];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
    NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
    if (data) {
        
        NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
            
            [receiveStatusDic setValue:@"1" forKey:@"status"];
            [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
        }else{
            
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
    }else{
        [receiveStatusDic setValue:@"-1" forKey:@"status"];
    }
    
    [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
}];  

}  
-(void)receiveData:(id)sender  
{  
NSLog(@"receiveData=%@",sender);  //打印獲取到的版本號

}

7三、取消全部響應者(關閉全部鍵盤)

//取消窗口第一響應
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

7四、加載html時候 讓大圖不超出屏幕

//css 控制
<head><style>img{width:100%% !important;}</style></head>
//js 控制
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = /"function ResizeImages() { "
         "var myimg,oldwidth,oldheight;"
         "var maxwidth=320;"// 圖片寬度
         "for(i=0;i  maxwidth){"
         "myimg.width = maxwidth;"
         "}"
         "}"
         "}/";"
         "document.getElementsByTagName('head')[0].appendChild(script);"];
         [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
     }

7五、監聽textfiled的輸入狀況

#pragma mark   UITextField   ----監聽

[timesField addTarget:self
               action:@selector(textFieldDidChange:)
     forControlEvents:UIControlEventEditingChanged]; // 監聽事件

監聽事件:

// 監聽改變按鈕
- (void) textFieldDidChange:(UITextField*) textField {
    
   
}

 

7六、頁面跳轉返回按鈕的文字

///設置push 以後返回按鈕的 字體
UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];
backbutton.title = @"";
self.navigationItem.backBarButtonItem = backbutton;

7七、/跳轉以後隱藏  返回鍵

life.navigationItem.hidesBackButton = YES;

7八、計算webview的高

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;

    NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
}

7九、設置陰影

#pragma mark  //設置 陰影
    [[self.calendarView layer] setShadowOffset:CGSizeMake(0, 0)];
    [[self.calendarView  layer] setShadowRadius:3];
    [[self.calendarView  layer] setShadowOpacity:0.4] ;
    [[self.calendarView  layer] setShadowColor:[UIColor blackColor].CGColor];

80、對鍵盤的監聽

#pragma mark 鍵盤監聽

[[NSNotificationCenter defaultCenter] addObserver:self
 
                                         selector:@selector(keyboardWasShown:)
 
                                             name:UIKeyboardWillShowNotification object:nil];

//註冊鍵盤消失的通知

[[NSNotificationCenter defaultCenter] addObserver:self
 
                                         selector:@selector(keyboardWillBeHidden:)
 
                                             name:UIKeyboardWillHideNotification object:nil];

- (void)keyboardWasShown:(NSNotification*)aNotification

{
    
    //鍵盤高度
    NSDictionary *userInfo = [aNotification userInfo];
    //NSLog(@"%@",userInfo);
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSInteger height = keyboardRect.size.height;
    
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
}


-(void)keyboardWillBeHidden:(NSNotification*)aNotification

{
    
    
}

8一、禁止webview 滾動

#pragma mark //禁止微webview 上下拖動
UIWebView * d_intro = [[UIWebView alloc] init];
d_intro.delegate = self;
d_intro.dataDetectorTypes = UIDataDetectorTypeLink;
//取消右側,下側滾動條,去處上下滾動邊界的黑色背景
d_intro.backgroundColor=[UIColor clearColor];
for (UIView *_aView in [d_intro subviews])
{
    if ([_aView isKindOfClass:[UIScrollView class]])
    {
        [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
        //右側的滾動條
        
        [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
        //下側的滾動條
        
        for (UIView *_inScrollview in _aView.subviews)
        {
            if ([_inScrollview isKindOfClass:[UIImageView class]])
            {
                _inScrollview.hidden = YES;  //上下滾動出邊界時的黑色的圖片
            }
        }
    }
}
[self.view addSubview:d_intro];

8二、圖片保存本地沙盒、

#pragma mark 圖片保存沙盒
- (void)setHeadBgImage
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"selfPhoto%d.jpg", [LoginManager sharedManager].userBasicInfo.uid]];
    success = [fileManager fileExistsAtPath:imageFilePath];
    UIImage *image1 = nil;
    if ([LoginManager sharedManager].loginSucess) {
        if (success) {
            NSData *data = [fileManager contentsAtPath:imageFilePath];
            image1 = [UIImage imageWithData:data];
        }
    }else{
        image1 = [UIImage imageNamed:@"account_head_bg"];
    }
    // NSLog(@"%@-%u",imageFilePath,success);
    
    [self setHeadBGImage:image1];
}




- (void)saveImage:(UIImage *)image
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"selfPhoto%d.jpg", [LoginManager sharedManager].userBasicInfo.uid]];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if (success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    BOOL result = [UIImagePNGRepresentation(image)writeToFile: imageFilePath    atomically:YES]; // 保存成功會返回YES
    //UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(self.view.frame.size.width, 315)];
    NSLog(@"%@-%u",imageFilePath,result);
    
    [self setHeadBGImage:image];
}

8三、圖片旋轉360度

#pragma mark //旋轉360 度 動畫
-(void) startAnimation
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.01];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(endAnimation)];
    _rechargeCover.transform = CGAffineTransformMakeRotation(angle * (M_PI / 180.0f));
    NSLog(@"%f",angle * (M_PI / 180.0f));
    [UIView commitAnimations];
    
}
-(void)endAnimation
{
    angle += 10;
    if (angle < 360) {
        [self startAnimation];
    }
    
}

8四、經常使用宏

#define DeviceMaxHeight ([UIScreen mainScreen].bounds.size.height)
#define DeviceMaxWidth ([UIScreen mainScreen].bounds.size.width)
#define widthRate DeviceMaxWidth/320
#define IOS8 ([[UIDevice currentDevice].systemVersion intValue] >= 8 ? YES : NO)
// RGB顏色
#define UIColorFromRGB1(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

8五、獲取故事版的 vc

UIStoryboard *login = [UIStoryboard storyboardWithName:@"LoginModule" bundle:nil];
AlsNoticeController* alsNoticeController = [login instantiateViewControllerWithIdentifier:@"LoginVC"];
[self.navigationController pushViewController:alsNoticeController animated:YES];

 

8六、設置windows覆蓋層

#pragma mark  //設置覆蓋層視圖
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"guideFirst"])  {
    _guideCoverView =[[UIView alloc]initWithFrame:self.view.bounds];
    _guideCoverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
    [currentWindow addSubview:_guideCoverView];
    

}

8七、設置透明度而且不影響子視圖

#pragma mark 視圖透明度 不影響子視圖
alterView.backgroundColor=[[UIColor whiteColor] colorWithAlphaComponent:1];

8八、剪切板的複製

#pragma mark 複製到系統剪切版
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

pasteboard.string = self.label.text;

8九、cocoPods經常使用指令

#pragma mark cocosPods指令
pod install --verbose --no-repo-update

pod list  列出全部可用的第三方庫

pod search query 搜包含query的第三方庫   注意:這兩個命令只搜存在於本地 /Users/yohunl/.cocoapods/ 下的文件

若是搜索網絡的,能夠先更新本地  pod repo update master,而後再搜索

pod lib create frameworkName  建立一個framework工程

pod lib lint 驗證一個podspec文件是否有錯誤

podinstall --no-repo-update錯誤 這裏的參數—no-repo-update,是告訴cocoapods不要更新repo.有麼有感受每次pod install都很慢,那是由於每一次都會先更新本地的repo,加上此參數,就跳過了這個過程,將會很快

pod init 能夠創建一個空的podfile

創建pod的spec文件   pod spec create spec名字  http://www.theonlylars.com/blog/2013/01/20/cocoapods-creating-a-pod-spec/

pod install 命令時會引起許多操做。要想深刻了解這個命令執行的詳細內容,能夠在這個命令後面加上 --verbose

 90、背景圖片按照某個像素拉伸web

self.messageImage.image = [[UIImage imageNamed:@"bbs_meaasge_frame"] stretchableImageWithLeftCapWidth:150 topCapHeight:20];
相關文章
相關標籤/搜索