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

1. 打印View所有子視圖

po [[self view]recursiveDescription]

2. layoutSubviews調用的調用時機

* 當視圖第一次顯示的時候會被調用

* 當這個視圖顯示到屏幕上了,點擊按鈕

* 添加子視圖也會調用這個方法

* 當本視圖的大小發生改變的時候是會調用的

* 當子視圖的frame發生改變的時候是會調用的

* 當刪除子視圖的時候是會調用的

3. NSString過濾特殊字符

// 定義一個特殊字符的集合

NSCharacterSet*set = [NSCharacterSetcharacterSetWithCharactersInString:

@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^?'@#$%^&*()_+'\""];

// 過濾字符串的特殊字符

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提示宏定義


1#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:^(BOOLfinished) {

exit(0);

}];

}

10. NSArray 快速求總和 最大值 最小值 和 平均值


NSArray*array = [NSArrayarrayWithObjects:@"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

{

[selfeditStringColor:self.label.text editStr:@"好"color:[UIColor blueColor]];

}

- (void)editStringColor:(NSString*)string editStr:(NSString*)editStr color:(UIColor *)color {

// string為整體字符串, editStr為需要修改的字符串

NSRangerange = [string rangeOfString:editStr];

NSMutableAttributedString*attribute = [[NSMutableAttributedStringalloc] initWithString:string];

// 設置屬性修改字體顏色UIColor與大小UIFont

[attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];

self.label.attributedText = attribute;

}

11. 播放聲音


#import

//? 1.獲取音效資源的路徑

NSString*path = [[NSBundlemainBundle]pathForResource:@"pour_milk"ofType:@"wav"];

//? 2.將路勁轉化為url

NSURL*tempUrl = [NSURLfileURLWithPath: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;

BOOLisIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;

BOOLhasIPadProWidth = 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 =

[[NSMutableAttributedStringalloc] initWithString:self.contentLabel.text];

NSMutableParagraphStyle*paragraphStyle =? [[NSMutableParagraphStylealloc] 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:[NSCharacterSetwhitespaceCharacterSet]];

- (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的小對勾的顏色改成別的顏色

[Objective-C]查看源文件復制代碼

?

1_mTableView.tintColor = [UIColor redColor];

38. 調整tableview的separaLine線的位置

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

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


1navigationController.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. 隱藏導航欄上的返回字體

//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:YESanimated:YES];

}else{

[self.navigationController setNavigationBarHidden:NOanimated: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:NOanimated:YES];

}else{

//上滑趨勢,隱藏

[self.navigationController setNavigationBarHidden:YESanimated:YES];

}

}else{

[self.navigationController setNavigationBarHidden:NOanimated: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 設置字體顏色

NSRangeblueRange =NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length);

[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:blueRange];

NSRangeblueRange1 =NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length);

[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:blueRange1];

//設置每行之間的間距

//NSParagraphStyleAttributeName 設置段落的樣式

NSMutableParagraphStyle* par = [[NSMutableParagraphStylealloc]init];

[par setLineSpacing:20];

//為某一范圍內文字添加某個屬性

//NSMakeRange表示所要的范圍,從0到整個文本的長度

[str addAttribute:NSParagraphStyleAttributeNamevalue:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];

效果圖

48. 點擊button倒計時

//第一種方法


//第一種方法

//點擊button倒計時

#import "ViewController.h"

@interfaceViewController ()

@property(nonatomic, strong) UIButton * timeButton;

@property(nonatomic, strong)NSTimer* timer;

@property(nonatomic, strong)UIButton * btn;

@end@implementationViewController

{

NSInteger_time;

}

- (void)viewDidLoad {

[superviewDidLoad];

_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:selfaction:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

[selfrefreshButtonWidth];

[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:[selfimageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];

[_btn setBackgroundImage:[selfimageWithColor:[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;

[selfrefreshButtonWidth];

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

_timer = [NSTimerscheduledTimerWithTimeInterval:0.1 target:selfselector:@selector(timeDown) userInfo:nilrepeats:YES];

}

- (void)timeDown{

_time --;

if(_time == 0) {

[_btn setTitle:@"重新獲取"forState:UIControlStateNormal]; _btn.enabled =YES;

[selfrefreshButtonWidth];

[_timer invalidate];

_timer =nil;

_time = 5 ;

return;

}

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

}


//第二種方法

#pragma mark -點擊發送驗證碼

- (void)sendMessage:(UIButton *)btn{

if(self.phoneField.text.length == 0) {

[selfremindMessage:@"請輸入正確的手機號"];

}else{

__blockinttimeout=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{

intseconds = timeout % 60;

NSString*strTime = [NSStringstringWithFormat:@"%d", seconds];

if([strTime isEqualToString:@"0"]) {

strTime = [NSStringstringWithFormat:@"%d",60];

}

dispatch_async(dispatch_get_main_queue(), ^{

//設置界面的按鈕顯示 根據自己需求設置

//NSLog(@"____%@",strTime);

[UIView beginAnimations:nilcontext:nil];

[UIView setAnimationDuration:1];

[btn setTitle:[NSStringstringWithFormat:@"%@秒后重新發送",strTime] forState:UIControlStateNormal];

[UIView commitAnimations];

btn.userInteractionEnabled =NO;

});

timeout--;

}

});

dispatch_resume(_timer);

}

效果圖

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

[Objective-C]查看源文件復制代碼

?

1textField.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!"; [/p][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顏色

2

_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.3 animations:^{

imageView.transform = CGAffineTransformMakeScale(2, 2);

} completion:^(BOOLfinished) {

imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);

}];

58. UIImage與字符串互轉

//圖片轉字符串

-(NSString*)UIImageToBase64Str:(UIImage *) image

{

NSData*data = UIImageJPEGRepresentation(image, 1.0f);

NSString*encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

returnencodedImageStr;

}

//字符串轉圖片

-(UIImage *)Base64StrToUIImage:(NSString*)_encodedImageStr

{

NSData*_decodedImageData?? = [[NSDataalloc] initWithBase64Encoding:_encodedImageStr];

UIImage *_decodedImage????? = [UIImage imageWithData:_decodedImageData];

return_decodedImage;

}

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


-(BOOL)isChinese:(NSString*)str{

NSString*match=@"(^[\u4e00-\u9fa5]+$)";

NSPredicate*predicate = [NSPredicatepredicateWithFormat:@"SELF matches %@", match];

return[predicate evaluateWithObject:str];

}

60. NSDate與NSString的相互轉化

-(NSString*)dateToString:(NSDate*)date {

// 初始化時間格式控制器

NSDateFormatter*matter = [[NSDateFormatteralloc] init];

// 設置設計格式

[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];

// 進行轉換

NSString*dateStr = [matter stringFromDate:date];

returndateStr;

}

-(NSDate*)stringToDate:(NSString*)dateStr {

// 初始化時間格式控制器

NSDateFormatter*matter = [[NSDateFormatteralloc] init];

// 設置設計格式

[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];

// 進行轉換

NSDate*date = [matter dateFromString:dateStr];

returndate;

}

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

推薦閱讀更多精彩內容

  • 獲取磁盤總空間大小 //磁盤總空間 (CGFloat)diskOfAllSizeMBytes{CGFloat si...
    UILabelkell閱讀 1,352評論 0 2
  • 打印View所有子視圖 layoutSubviews調用的調用時機 當視圖第一次顯示的時候會被調用當這個視圖顯示到...
    hyeeyh閱讀 524評論 0 3
  • 一.觀察者模式介紹 觀察者模式是一個使用率非常高的模式,它最常用的地方是GUI系統,訂閱-發布系統。因為這個模式的...
    Android開發知識總結閱讀 1,187評論 8 6
  • 昨晚我又夢見你了,還是和以往一樣,沒敢和你講話,怕被你發現。 夢里綠蔭道兩旁超大的樹,當然如果用電線桿子來行容那是...
    靜言思之lqr閱讀 108評論 0 0
  • 談戀愛就應該經歷一下異地戀,體會一下欣喜憂愁無從分享,歡笑落淚不能擁抱,隔著屏幕隔著電話隔著書信聯系直到你幾乎發瘋...
    阿花呀_閱讀 136評論 0 1