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

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

//SwiftUIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)

//OC[[UIBarButtonItemappearance]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這個值在較小幅度上下滑動時,可能都為正或都為負,這就使得這一方式不太靈敏.

效果圖

46. 設置導航欄透明

//方法一:設置透明度

[[[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];

}

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];

效果圖

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();returnimage;

}

- (void)btnAction:(UIButton *)sender{

sender.enabled = NO;

[self refreshButtonWidth];

[sender setTitle:[NSString stringWithFormat:@"獲取驗證碼(%zi)", _time] forState:UIControlStateNormal];

_timer = [NSTimer scheduledTimerWithTimeInterval:0.1target: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_tqueue=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);}

效果圖

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=[imgresizableImageWithCapInsets:edgeresizingMode: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);

? }elseif(scrollView.contentOffset.y >= sectionHeaderHeight) {? ?

? scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0);? ? ? ?

?? }? ? ? }? }

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

[UIView animateWithDuration:0.3animations:^{ ?

?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];

returnen codedImageStr;?

?}

//字符串轉圖片?

?-(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];returndateStr;

}

-(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;

}


文章出處:iOS 知識-常用小技巧大雜燴

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容