1,打印View所有子視圖
po[[selfview]recursiveDescription]
2,layoutSubviews調用的調用時機
* 當視圖第一次顯示的時候會被調用
* 當這個視圖顯示到屏幕上了,點擊按鈕
* 添加子視圖也會調用這個方法
* 當本視圖的大小發生改變的時候是會調用的
* 當子視圖的frame發生改變的時候是會調用的
* 當刪除子視圖的時候是會調用的
3,NSString過濾特殊字符
// 定義一個特殊字符的集合
NSCharacterSet *set = [NSCharacterSetcharacterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-*+=_\|~<>$€^•'@#$%^&*()_+'""];
// 過濾字符串的特殊字符
NSString *newString = [trimStringstringByTrimmingCharactersInSet:set];
4,TransForm屬性
//平移按鈕
CGAffineTransformtransForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm,10,0);
//旋轉按鈕
CGAffineTransformtransForm = 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.tableViewrespondsToSelector:@selector(setSeparatorInset:)]){
[self.tableViewsetSeparatorInset:UIEdgeInsetsZero];
}
if([self.tableViewrespondsToSelector:@selector(setLayoutMargins:)]){
[self.tableViewsetLayoutMargins:UIEdgeInsetsZero];
}
然後在重寫willDisplayCell方法
-(void)tableView:(UITableView *)tableViewwillDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath{
if([cellrespondsToSelector:@selector(setSeparatorInset:)]){
[cellsetSeparatorInset:UIEdgeInsetsZero];
}
if([cellrespondsToSelector:@selector(setLayoutMargins:)]){
[cellsetLayoutMargins: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]
8,讓 iOS 應用直接退出
-(void)exitApplication{
AppDelegate *app = [UIApplicationsharedApplication].delegate;
UIWindow *window = app.window;
[UIViewanimateWithDuration:1.0fanimations:^{
window.alpha = 0;
}completion:^(BOOLfinished){
exit(0);
}];
}
8,NSArray 快速求總和 最大值 最小值 和 平均值
NSArray *array = [NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil];
CGFloatsum = [[arrayvalueForKeyPath:@"@sum.floatValue"]floatValue];
CGFloatavg = [[arrayvalueForKeyPath:@"@avg.floatValue"]floatValue];
CGFloatmax =[[arrayvalueForKeyPath:@"@max.floatValue"]floatValue];
CGFloatmin =[[arrayvalueForKeyPath:@"@min.floatValue"]floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
9,修改Label中不同文字顏色
-(void)touchesEnded:(NSSet *)toucheswithEvent:(UIEvent *)event
{
[selfeditStringColor:self.label.texteditStr:@"好"color:[UIColorblueColor]];
}
-(void)editStringColor:(NSString *)stringeditStr:(NSString *)editStrcolor:(UIColor *)color{
// string爲整體字符串, editStr爲需要修改的字符串
NSRangerange = [stringrangeOfString:editStr];
NSMutableAttributedString *attribute = [[NSMutableAttributedStringalloc]initWithString:string];
// 設置屬性修改字體顏色UIColor與大小UIFont
[attributeaddAttributes:@{NSForegroundColorAttributeName:color}range:range];
self.label.attributedText = attribute;
}
10,播放聲音
#import
// 1.獲取音效資源的路徑
NSString *path = [[NSBundlemainBundle]pathForResource:@"pour_milk"ofType:@"wav"];
// 2.將路勁轉化爲url
NSURL *tempUrl = [NSURLfileURLWithPath:path];
// 3.用轉化成的url創建一個播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayeralloc]initWithContentsOfURL:tempUrlerror:&error];
self.player = play;
// 4.播放
[playplay];
11,檢測是否IPad Pro和其它設備型號
-(BOOL)isIpadPro
{
UIScreen *Screen = [UIScreenmainScreen];
CGFloatwidth = Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloatheight = Screen.nativeBounds.size.height/Screen.nativeScale;
BOOLisIpad =[[UIDevicecurrentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPad;
BOOLhasIPadProWidth = fabs(width - 1024.f) = 8.0)
11,修改Tabbar Item的屬性
// 修改標題位置
self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
// 修改圖片位置
self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3,0,3,0);
// 批量修改屬性
for(UIBarItem *item inself.tabBarController.tabBar.items){
[itemsetTitleTextAttributes:[NSDictionarydictionaryWithObjectsAndKeys:
[UIFontfontWithName:@"Helvetica"size:19.0],NSFontAttributeName,nil]
forState:UIControlStateNormal];
}
// 設置選中和未選中字體顏色
[[UITabBarappearance]setShadowImage:[[UIImagealloc]init]];
//未選中字體顏色
[[UITabBarItemappearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColorgreenColor]}forState:UIControlStateNormal];
//選中字體顏色
[[UITabBarItemappearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColorcyanColor]}forState:UIControlStateSelected];
12,NULL – nil – Nil – NSNULL的區別
* nil是OC的,空對象,地址指向空(0)的對象。對象的字面零值
* Nil是Objective-C類的字面零值
* NULL是C的,空地址,地址的數值是0,是個長整數
* NSNull用於解決向NSArray和NSDictionary等集合中添加空值的問題
11,去掉BackBarButtonItem的文字
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
12,控件不能交互的一些原因
1,控件的userInteractionEnabled = NO
2,透明度小於等於0.01,aplpha
3,控件被隱藏的時候,hidden = YES
4,子視圖的位置超出了父視圖的有效範圍,子視圖無法交互,設置了。
5,需要交互的視圖,被其他視圖蓋住(其他視圖開啓了用戶交互)。
12,修改UITextField中Placeholder的文字顏色
[textsetValue:[UIColorredColor]forKeyPath:@"_placeholderLabel.textColor"];
13,視圖的生命週期
1、alloc創建對象,分配空間
2、init(initWithNibName)初始化對象,初始化數據
3、loadView從nib載入視圖,除非你沒有使用xib文件創建視圖
4、viewDidLoad載入完成,可以進行自定義數據以及動態創建其他控件
5、viewWillAppear視圖將出現在屏幕之前,馬上這個視圖就會被展現在屏幕上了
6、viewDidAppear視圖已在屏幕上渲染完成
1、viewWillDisappear視圖將被從屏幕上移除之前執行
2、viewDidDisappear視圖已經被從屏幕上移除,用戶看不到這個視圖了
3、dealloc視圖被銷燬,此處需要對你在init和viewDidLoad中創建的對象進行釋放.
viewVillUnload-當內存過低,即將釋放時調用;
viewDidUnload-當內存過低,釋放一些不需要的視圖時調用。
14,應用程序的生命週期
1,啓動但還沒進入狀態保存:
-(BOOL)application:(UIApplication *)applicationwillFinishLaunchingWithOptions:(NSDictionary *)launchOptions
2,基本完成程序準備開始運行:
-(BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
3,當應用程序將要入非活動狀態執行,應用程序不接收消息或事件,比如來電話了:
-(void)applicationWillResignActive:(UIApplication *)application
4,當應用程序入活動狀態執行,這個剛好跟上面那個方法相反:
-(void)applicationDidBecomeActive:(UIApplication *)application
5,當程序被推送到後臺的時候調用。所以要設置後臺繼續運行,則在這個函數裏面設置即可:
-(void)applicationDidEnterBackground:(UIApplication *)application
6,當程序從後臺將要重新回到前臺時候調用,這個剛好跟上面的那個方法相反:
-(void)applicationWillEnterForeground:(UIApplication *)application
7,當程序將要退出是被調用,通常是用來保存數據和一些退出前的清理工作:
-(void)applicationWillTerminate:(UIApplication *)application
15,判斷view是不是指定視圖的子視圖
BOOLisView = [textViewisDescendantOfView:self.view];
16,判斷對象是否遵循了某協議
if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)]){
[self.selectedControllerperformSelector:@selector(onTriggerRefresh)];
}
17,頁面強制橫屏
#pragma mark - 強制橫屏代碼
-(BOOL)shouldAutorotate{
//是否支持轉屏
returnNO;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
//支持哪些轉屏方向
returnUIInterfaceOrientationMaskLandscape;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
returnUIInterfaceOrientationLandscapeRight;
}
-(BOOL)prefersStatusBarHidden{
returnNO;
}
18,系統鍵盤通知消息
1、UIKeyboardWillShowNotification-將要彈出鍵盤
2、UIKeyboardDidShowNotification-顯示鍵盤
3、UIKeyboardWillHideNotification-將要隱藏鍵盤
4、UIKeyboardDidHideNotification-鍵盤已經隱藏
5、UIKeyboardWillChangeFrameNotification-鍵盤將要改變frame
6、UIKeyboardDidChangeFrameNotification-鍵盤已經改變frame
19,關閉navigationController的滑動返回手勢
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
20,設置狀態欄背景爲任意的顏色
-(void)setStatusColor
{
UIView *statusBarView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,[UIScreenmainScreen].bounds.size.width,20)];
statusBarView.backgroundColor = [UIColororangeColor];
[self.viewaddSubview:statusBarView];
}
21,讓Xcode的控制檯支持LLDB類型的打印
打開終端輸入三條命令:
touch ~/.lldbinit
echodisplay@importUIKit >> ~/.lldbinit
echo target stop-hookadd -o"target stop-hook disable" >> ~/.lldbinit
下次重新運行項目,然後就不報錯了。
22,Label行間距
-(void)test{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedStringalloc]initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc]init];
[paragraphStylesetLineSpacing:3];
//調整行間距
[attributedStringaddAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0,[self.contentLabel.textlength])];
self.contentLabel.attributedText = attributedString;
}
23,UIImageView填充模式
@"UIViewContentModeScaleToFill", // 拉伸自適應填滿整個視圖
@"UIViewContentModeScaleAspectFit", // 自適應比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下
24,宏定義檢測block是否可用
#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };
// 宏定義之前的用法
if(completionBlock) {
completionBlock(arg1,arg2);
}
// 宏定義之後的用法
BLOCK_EXEC(completionBlock,arg1,arg2);
25,Debug欄打印時自動把Unicode編碼轉化成漢字
// 有時候我們在xcode中打印中文,會打印出Unicode編碼,還需要自己去一些在線網站轉換,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin插件
26,設置狀態欄文字樣式顏色
[[UIApplicationsharedApplication]setStatusBarHidden:NO];
[[UIApplicationsharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
26,自動生成模型代碼的插件
// 可自動生成模型的代碼,省去寫模型代碼的時間
ESJsonFormat-for-Xcode
27,iOS中的一些手勢
輕擊手勢(TapGestureRecognizer)
輕掃手勢(SwipeGestureRecognizer)
長按手勢(LongPressGestureRecognizer)
拖動手勢(PanGestureRecognizer)
捏合手勢(PinchGestureRecognizer)
旋轉手勢(RotationGestureRecognizer)
27,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/ProvisioningProfiles
28,獲取 iOS 路徑的方法
獲取家目錄路徑的函數
NSString *homeDir = NSHomeDirectory();
獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [pathsobjectAtIndex:0];
獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesDir = [pathsobjectAtIndex:0];
獲取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();
29,字符串相關操作
去除所有的空格
[strstringByReplacingOccurrencesOfString:@" "withString:@""]
去除首尾的空格
[strstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
-(NSString *)uppercaseString;全部字符轉爲大寫字母
-(NSString *)lowercaseString全部字符轉爲小寫字母