iOS常用的宏

語言

// 當(dāng)前語言
#define CURRENTLANGUAGE   ([[NSLocale preferredLanguages] objectAtIndex:0])

## ****本地化

// 本地化字符串
/** NSLocalizedString宏做的其實就是在當(dāng)前bundle中查找資源文件名“Localizable.strings”(參數(shù):鍵+注釋) */
#define LocalString(x, ...)     NSLocalizedString(x, nil)
/** NSLocalizedStringFromTable宏做的其實就是在當(dāng)前bundle中查找資源文件名“xxx.strings”(參數(shù):鍵+文件名+注釋) */
#define AppLocalString(x, ...) NSLocalizedStringFromTable(x, @"zjj", nil)

## ****打印

#ifdef DEBUG
#define DLog(fmt, ...) {NSLog((@"%s [Line %d]" fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);}
#else
#define DLog(...)
#endif

## ****設(shè)備及系統(tǒng)型號

// 判斷是否 Retina屏、設(shè)備是否%fhone 5、是否是iPad
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

// 判斷設(shè)備的操做系統(tǒng)是不是ios7
#define IOS7 ([[[UIDevice currentDevice].systemVersion doubleValue] >= 7.0]

// 判斷設(shè)備的操做系統(tǒng)是不是ios8
#define IOS8 ([[[UIDevice currentDevice].systemVersion doubleValue] >= 8.0]

// 判斷設(shè)備的操做系統(tǒng)是不是ios9
#define IOS9 ([[[UIDevice currentDevice].systemVersion doubleValue] >= 9.0]

// 判斷當(dāng)前設(shè)備是不是iPhone4或者4s
#define IPHONE4S    (([[UIScreen mainScreen] bounds].size.height)==480)

// 判斷當(dāng)前設(shè)備是不是iPhone5
#define IPHONE5    (([[UIScreen mainScreen] bounds].size.height)==568)

// 判斷當(dāng)前設(shè)備是不是iPhone6
#define IPHONE6    (([[UIScreen mainScreen] bounds].size.height)==667)

// 判斷當(dāng)前設(shè)備是不是iPhone6Plus
#define IPHONE6_PLUS    (([[UIScreen mainScreen] bounds].size.height)>=736)

// 獲取當(dāng)前屏幕的高度
#define kMainScreenHeight ([UIScreen mainScreen].applicationFrame.size.height)

// 獲取當(dāng)前屏幕的寬度
#define kMainScreenWidth  ([UIScreen mainScreen].applicationFrame.size.width)

// 判斷是真機還是模擬器
#if TARGET_OS_IPHONE
// iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
// iPhone Simulator

#endif

## ****獲取系統(tǒng)版本

// 獲取系統(tǒng)版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define CurrentSystemVersion [[UIDevice currentDevice] systemVersion]

## ****獲取****RGB****顏色

// 獲取RGB顏色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]

## G - C - D****定義

// 延時GCD
#define dispatch_after(time, block) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), block);

// 使用
dispatch_after(2, ^{
        // 延時代碼
    });
    
// 主線程
#define dispatch_main_queue(block) dispatch_async(dispatch_get_main_queue(), block)

// 子線程
#define dispatch_global_queue(block)  dispatch_async(dispatch_get_global_queue(0, 0), block)    

## ****常量定義

static CGFloat const kLogoImageWidth = 100; //logo寬度
static CGFloat const kLogoImageHeight = 100; //logo寬度static CGFloat const kLogoImageY = 110;
static CGFloat const kBtnHeight = 40;
static CGFloat const kPadding = 30;
static CGFloat const kWeixinTopPadding = 15;
static CGFloat const kWeiboLoginBottom = 230;
#define kScaleSpace(designSpace) ((designSpace)(SCREEN_HEIGHT/667.0)) //根據(jù)iphone6 的設(shè)計稿計算縮放高度

static CGFloat const kBottomHeight = 50.0; //底部視圖高度
static NSString   *const CELL_TITLE_KEY = @"CELL_TITLE_KEY";
static NSString   *const CELL_CONTENT_KEY = @"CELL_CONTENT_KEY";

補充說明:以上的類型常量替換宏的情況,只是適用于單個文件的情況。如果是多個文件共享的常量,蘋果推薦的這樣的方式:

*  UserInfoModelConstants.h

extern NSString *const USER_AGE_KEY         ;
extern NSString *const USER_TELPHONE_KEY    ;
extern NSString *const USER_ADDRESS_KEY     ;
extern NSString *const USER_BRIEF_KEY       ;

*  UserInfoModelConstants.m

NSString *const BKUSER_AGE_KEY         =     @"XXXXX.userAge";
NSString *const BKUSER_TELPHONE_KEY    =     @"XXXXX.telphoneNO";
NSString *const BKUSER_ADDRESS_KEY     =     @"XXXXX.address"; 
NSString *const BKUSER_BRIEF_KEY       =     @"XXXXX.brief";

## Block

// 無返回值block
//@property (nonatomic, copy) void (^editBlock)();
@property (nonatomic, copy) dispatch_block_t editBlock;

## ****打印****View****所有子視圖

po [[self view]recursiveDescription]

## layoutSubviews****調(diào)用的調(diào)用時機

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

## NSString****過濾特殊字符

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

## TransForm****屬性

//平移按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);

//旋轉(zhuǎn)按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);

//縮放按鈕
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化復(fù)位
self.buttonView.transform = CGAffineTransformIdentity;

## ****去掉分割線多余****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];    
    }
}

## ****計算方法耗時時間間隔

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

## Alert****提示宏定義

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

## ****讓**** iOS ****應(yīng)用直接退出

- (void)exitApplication {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;

    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
    } completion:^(BOOL finished) {
        exit(0);
    }];
}

## ****修改****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];

    // 設(shè)置屬性修改字體顏色UIColor與大小UIFont
    [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];

    self.label.attributedText = attribute;
}

## ****播放聲音

#import<AVFoundation/AVFoundation.h>
// 1.獲取音效資源的路徑
NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
// 2.將路勁轉(zhuǎn)化為url
NSURL *tempUrl = [NSURL fileURLWithPath:path];
// 3.用轉(zhuǎn)化成的url創(chuàng)建一個播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self.player = play;
//  4.播放
[play play];

## ****修改****Tabbar Item****的屬性

 // 修改標(biāo)題位置
    self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
    // 修改圖片位置
    self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);

    // 批量修改屬性
    for (UIBarItem *item in self.tabBarController.tabBar.items) {
        [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                 [UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
                            forState:UIControlStateNormal];
    }

    // 設(shè)置選中和未選中字體顏色
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

    //未選中字體顏色
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];

    //選中字體顏色
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];

## ****去掉****BackBarButtonItem****的文字

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];

## ****視圖的生命周期

1、 alloc 創(chuàng)建對象,分配空間
2、 init (initWithNibName) 初始化對象,初始化數(shù)據(jù)
3、 loadView 從nib載入視圖 ,除非你沒有使用xib文件創(chuàng)建視圖
4、 viewDidLoad 載入完成,可以進(jìn)行自定義數(shù)據(jù)以及動態(tài)創(chuàng)建其他控件
5、 viewWillAppear視圖將出現(xiàn)在屏幕之前,馬上這個視圖就會被展現(xiàn)在屏幕上了
6、 viewDidAppear 視圖已在屏幕上渲染完成

1、viewWillDisappear 視圖將被從屏幕上移除之前執(zhí)行
2、viewDidDisappear 視圖已經(jīng)被從屏幕上移除,用戶看不到這個視圖了
3、dealloc 視圖被銷毀,此處需要對你在init和viewDidLoad中創(chuàng)建的對象進(jìn)行釋放.

viewVillUnload- 當(dāng)內(nèi)存過低,即將釋放時調(diào)用;
viewDidUnload-當(dāng)內(nèi)存過低,釋放一些不需要的視圖時調(diào)用。

## ****應(yīng)用程序的生命周期

1,啟動但還沒進(jìn)入狀態(tài)保存 :
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

2,基本完成程序準(zhǔn)備開始運行:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

3,當(dāng)應(yīng)用程序?qū)⒁敕腔顒訝顟B(tài)執(zhí)行,應(yīng)用程序不接收消息或事件,比如來電話了:
- (void)applicationWillResignActive:(UIApplication *)application 

4,當(dāng)應(yīng)用程序入活動狀態(tài)執(zhí)行,這個剛好跟上面那個方法相反:
- (void)applicationDidBecomeActive:(UIApplication *)application   

5,當(dāng)程序被推送到后臺的時候調(diào)用。所以要設(shè)置后臺繼續(xù)運行,則在這個函數(shù)里面設(shè)置即可:
- (void)applicationDidEnterBackground:(UIApplication *)application  

6,當(dāng)程序從后臺將要重新回到前臺時候調(diào)用,這個剛好跟上面的那個方法相反:
- (void)applicationWillEnterForeground:(UIApplication *)application  

7,當(dāng)程序?qū)⒁顺鍪潜徽{(diào)用,通常是用來保存數(shù)據(jù)和一些退出前的清理工作:
- (void)applicationWillTerminate:(UIApplication *)application

## ****判斷****view****是不是指定視圖的子視圖

 BOOL isView =  [textView isDescendantOfView:self.view];

## ****頁面強制橫屏

#pragma mark - 強制橫屏代碼
- (BOOL)shouldAutorotate{    
    //是否支持轉(zhuǎn)屏       
    return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{    
    //支持哪些轉(zhuǎn)屏方向    
    return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{               
    return UIInterfaceOrientationLandscapeRight;
}
- (BOOL)prefersStatusBarHidden{   
    return NO;
}

## ****系統(tǒng)鍵盤通知消息

1、UIKeyboardWillShowNotification - 將要彈出鍵盤
2、UIKeyboardDidShowNotification  - 顯示鍵盤
3、UIKeyboardWillHideNotification - 將要隱藏鍵盤
4、UIKeyboardDidHideNotification  - 鍵盤已經(jīng)隱藏
5、UIKeyboardWillChangeFrameNotification - 鍵盤將要改變frame
6、UIKeyboardDidChangeFrameNotification  - 鍵盤已經(jīng)改變frame

## ****關(guān)閉****navigationController****的滑動返回手勢

self.navigationController.interactivePopGestureRecognizer.enabled = NO;

## ****設(shè)置狀態(tài)欄為任意的顏色

- (void)setStatusColor
{
    UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    statusBarView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:statusBarView];
}

## ****讓****Xcode****的控制臺支持****LLDB****類型的打印

打開終端輸入三條命令:
    touch ~/.lldbinit
    echo display @import UIKit >> ~/.lldbinit
    echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

下次重新運行項目,然后就不報錯了。


## Label****行間距

-(void)test{
    NSMutableAttributedString *attributedString =    
   [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
    NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];  
   [paragraphStyle setLineSpacing:3];

    //調(diào)整行間距       
   [attributedString addAttribute:NSParagraphStyleAttributeName 
                         value:paragraphStyle 
                         range:NSMakeRange(0, [self.contentLabel.text length])];
     self.contentLabel.attributedText = attributedString;
}

## UIImageView****填充模式

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容