IOS開發-OC學習-常用功能代碼片段整理
IOS開發中會頻繁用到一些代碼段,用來實現一些固定的功能。比如在文本框中輸入完后要讓鍵盤收回,這個需要用一個簡單的讓文本框失去第一響應者的身份來完成。或者是在做與URL有關的功能時,需要在Info.plist中添加一段代碼進而實現讓網址完成從Http到Https的轉換,如何使用定時器完成一些耗時的模擬以及其他的一些功能。
在從一個新手到逐漸學會各種功能、代碼、控件、方法如何使用的過程中,也在逐漸積累一些知識,但是一次總不會把這些東西都深刻記住並完全理解。所以在這兒記錄下這些東西,用來提醒自己,讓自己在以前花時間學過的知識上不要因為遺忘而花費更多的時間。
言歸正傳,以下是總結出來的常用代碼段的目錄(點擊可直接跳轉到代碼處):
三、如何獲取屏幕分辨率進而完成不同分辨率設備的UI布局自動適配。
以上目錄中中各功能的詳細代碼如下:
1 //輸入完后點擊輸入框空白處讓鍵盤消失 2 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 3 // password為文本輸入控件 4 [password resignFirstResponder]; 5 }
1 <key>NSAppTransportSecurity</key> 2 <dict> 3 <key>NSAllowsArbitraryLoads</key> 4 <true/> 5 </dict>
注意以上代碼段用法為:右鍵Info.plist文件並使用Source Code打開,然后在里面隨便一個鍵值對之后插入以上5行代碼,即可。
三、如何獲取屏幕分辨率進而完成不同分辨率設備的UI布局自動適配:
1 //屏幕尺寸 2 CGRect rect = [[UIScreen mainScreen] bounds]; 3 CGSize size = rect.size; 4 CGFloat width = size.width; 5 CGFloat height = size.height; 6 NSLog(@"print %f,%f",width,height); 7 8 //分辨率 9 CGFloat scale_screen = [UIScreen mainScreen].scale; 10 width*scale_screen,height*scale_screen
1、初始化定時器,設置定時間隔,觸發方法,是否重復等:
1 NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(load:) userInfo:nil repeats:YES];
2、設置定時器方法,在每個定時間隔出發一次方法,可以在方法中關閉定時器:
1 -(void)load:(id)sender{ 2 count++; 3 if (myProgressView.progress <1) { 4 5 myProgressView.progress += 0.01*count/10; 6 myLabel.text = [NSString stringWithFormat:@"%.0f%%",myProgressView.progress*100]; 7 8 }else{ 9 10 [myTimer invalidate]; 11 12 } 13 14 }
1、創建buttom:
1 // 創建buttom,初始化尺寸大小及定位
2 UIButton *myBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 214, 80)]; 3 // 設置背景色
4 myBtn.backgroundColor = [UIColor orangeColor]; 5 // 設置圓角
6 myBtn.layer.cornerRadius = 20; 7 // 設置圓角遮罩允許
8 myBtn.layer.masksToBounds = YES; 9 // 使能button,默認為YES
10 myBtn.enabled = YES; 11 // 設置文字
12 [myBtn setTitle:@"開始按鈕" forState:UIControlStateNormal]; 13 // 添加點擊事件
14 [myBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside]; 15 // 添加buttom到當前view
16 [self.view addSubview:myBtn];
2、添加點擊事件:
1 -(void)myBtnAction:(UIButton*)sender{ 2 sender.backgroundColor = [UIColor redColor]; 3 }
1 -(instancetype)init{ 2 if (self = [super init]) { 3 // 初始化設置 4 self.title = @"動畫"; 5 [self.tabBarItem setImage:[UIImage imageNamed:@"movie_projector_filled"]]; 6 } 7 // 返回self 8 return self; 9 }
舉一個例子,如果我們要在點擊一個按鍵之后,讓這個按鍵變透明,那我們的做法是在按鍵的觸發事件中讓按鍵的alpha值變為0就可以,但這樣的話當按下按鍵之后按鍵瞬間就變透明了,如果讓它逐漸變淡效果就會好很多,通過動畫就可以實現這種效果。可以通過設置動畫的時長來控制按鍵從開始變透明到結束需要的時間,具體代碼如下:
1 [UIView animateWithDuration:1 animations:^{ 2 <#code#> 3 } completion:^(BOOL finished) { 4 <#code#> 5 }]
其中animateWithDuration:1是設置動畫的時長為1s。
代碼中兩處<#code#>,第一個<#code#>的位置,就是你要添加的動畫的代碼,比如我想讓按鍵按下之后讓按鍵自己變透明,那就在第一個<#code#>處增加一句:
1 sender.alpha = 0;
想讓按鍵在完成1s的動畫之后又恢復原本的顏色,那就在第二個<#code#>的位置添加如下代碼:
1 sender.alpha = 1;
整體代碼如下:
1 -(void)btnAction:(UIButton *)sender{ 2 // 添加動畫,動畫時長為1s 3 [UIView animateWithDuration:1 animations:^{ 4 // 需要添加動畫效果的語句 5 sender.alpha = 0; 6 } completion:^(BOOL finished) { 7 // 動畫效果完成后的語句 8 sender.alpha = 1; 9 }]; 10 }
彈出框、警示框在軟件中是非常常用的,當用戶輸入了錯誤的用戶名或者密碼的時候,軟件彈出一個警示框告知用戶輸入錯誤,要求重新輸入或直接提供一個帳號密碼輸入框供用戶重新輸入,以下是一個警示框的完整代碼,放在被觸發的事件處理中就可以:
1 // 新建一個彈出框設置標題,提示內容,以及樣式 2 UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"這里時提示用" preferredStyle:UIAlertControllerStyleAlert]; 3 4 // 給彈出框添加輸入框 5 [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { 6 textField.keyboardType=UIKeyboardTypeDefault; 7 }]; 8 9 10 // 給彈出框設置密碼輸入框 11 [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { 12 textField.secureTextEntry=YES; 13 textField.keyboardType=UIKeyboardTypeNumberPad; 14 textField.returnKeyType=UIReturnKeySearch; 15 }]; 16 // 17 18 19 // 給彈出框增加警示作用的紅色按鈕 20 [alert addAction:[UIAlertAction actionWithTitle:@"警示" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { 21 NSLog(@"用戶點擊了取消"); 22 }]]; 23 24 // 給彈出框增加取消按鈕 25 [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 26 NSLog(@"用戶點擊了取消"); 27 }]]; 28 29 // 給彈出框增加確認按鈕點擊確認后讀取輸入框內容並打印 30 [alert addAction:[UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 31 NSLog(@"點擊了確認"); 32 33 // 讀取彈出框中的輸入框里的內容[[alert textFields]objectAtIndex:0].text,並打印
34 NSString *textfield0text =[[alert textFields]objectAtIndex:0].text;
35 NSString *textfield1text =[[alert textFields]objectAtIndex:1].text;
36 NSLog(@"%@ %@", textfield0text,textfield1text);
37
38 }]];
39
40 // 把彈出框呈現在控制器視圖上,選擇有動畫效果。這一步很關鍵。
41 [self presentViewController:alert animated:YES completion:nil];
1 // 創建並初始化菊花 2 activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 3 // 背景色,設置alpha為0,背景色是透明的 4 activity.backgroundColor = [UIColor colorWithRed:1.000 green:0.941 blue:0.912 alpha:0]; 5 // 設置中心為當前view的中心 6 activity.center = self.view.center; 7 // 設置菊花顏色 8 activity.color = [UIColor darkGrayColor]; 9 // 設置圓角 10 activity.layer.cornerRadius = 5; 11 activity.layer.masksToBounds = YES; 12 // 添加到當前view 13 [self.view addSubview:activity]; 14 // 開始旋轉菊花 15 [activity startAnimating]; 16 // 停止旋轉菊花 17 [activity stopAnimating];
1 // 初始化UITextView並設置位置,大小 2 myTextView = [[UITextView alloc]initWithFrame:CGRectMake(100, 100, 300, 200)]; 3 // 設置背景色 4 myTextView.backgroundColor = [UIColor grayColor]; 5 // 設置字體 6 myTextView.font = [UIFont systemFontOfSize:20.0]; 7 // 設置要顯示的文本 8 myTextView.text = @"this is a textview!"; 9 // 設置是否允許編輯 10 myTextView.editable = YES; 11 // 設置是否允許滑動 12 myTextView.scrollEnabled = YES; 13 // 設置文字對齊方式 14 myTextView.textAlignment = NSTextAlignmentLeft; 15 // 設置鍵盤返回鍵的類型 16 myTextView.returnKeyType = UIReturnKeySearch; 17 // 設置鍵盤類型 18 myTextView.keyboardType = UIKeyboardTypeNamePhonePad; 19 // 設置字體顏色 20 myTextView.textColor = [UIColor blackColor]; 21 // 添加到當前view 22 [self.view addSubview:myTextView];
通過給NSString類擴展一個方法,用來獲取字體高度,進而設置文本框的高度:
NSString+SizeToFit.h:
1 // 2 // NSString+SizeToFit.h 3 // constellation 4 // 5 // Created by Yuri on 15/7/21. 6 // Copyright (c) 2015年 XiaofeiZhang. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 #import <UIKit/UIKit.h> 11 @interface NSString (SizeToFit) 12 /** 13 *返回值是該字符串所占的大小(width, height) 14 *font : 該字符串所用的字體(字體大小不一樣,顯示出來的面積也不同) 15 *maxSize : 為限制改字體的最大寬和高(如果顯示一行,則寬高都設置為MAXFLOAT, 如果顯示為多行,只需將寬設置一個有限定長值,高設置為MAXFLOAT) 16 */ 17 -(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize; 18 @end
NSString+SizeToFit.m:
1 // 2 // NSString+SizeToFit.m 3 // constellation 4 // 5 // Created by Yuri on 15/7/21. 6 // Copyright (c) 2015年 XiaofeiZhang. All rights reserved. 7 // 8 9 #import "NSString+SizeToFit.h" 10 11 @implementation NSString (SizeToFit) 12 13 - (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize { 14 15 //返回字符串所占用的尺寸. 16 NSDictionary *attrs = @{NSFontAttributeName : font}; 17 return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; 18 19 } 20 @end
使用方法:
//textView的代理方法 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ // 計算mytextview.text的文字的高度並返回給size CGSize size = [mytextview.text sizeWithFont:[UIFont systemFontOfSize:20] maxSize:CGSizeMake(300, MAXFLOAT)]; // 使用計算的高度設置mytextview控件的高度 mytextview.frame = CGRectMake(0, 200, 300, size.height); return YES; }
這樣當在mytextview中輸入文字時,mytextview的高度就會發生變化。
1 // 打電話 其中XXXXXXXXXXX為要撥打的電話 2 NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"XXXXXXXXXXX"]; 3 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
1 [[UIDevice currentDevice]systemVersion];