iOS開發(fā)小經(jīng)驗(yàn)總結(jié)(持續(xù)更新中)

1.iphone尺寸

手機(jī) 型號(hào) 屏幕尺寸
iPhone 4 4s 320 * 480
iPhone 5 5s 320 * 568
iPhone 6 6s 375 * 667
iPhone 6Plus 6sPlus 414 * 736

2.兩個(gè)app之間跳轉(zhuǎn)

  1. 在app2的info.plist中定義URL,就是在文件中添加URL types一項(xiàng)。可按下圖進(jìn)行添加。


  2. 在app1的代碼中定義跳轉(zhuǎn),代碼如下:
NSURL *url = [NSURL URLWithString:@"myApp://"];
if ([[UIApplication sharedApplication] canOpenURL:url]){
    [[UIApplication sharedApplication] openURL:url];
}
  1. 打開之后,會(huì)調(diào)用app2的AppDelegate:
-(BOOL)application:(UIApplication*)app openURL:
(NSURL*)url options:(NSDictionary *)options{
}

3.navigation

  • 自定義leftNavigationBar左滑返回手勢(shì)失效
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:img 
                                          style:UIBarButtonItemStylePlain 
                                          target:self 
                                          action:@selector(onBack:)];
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
  • 滑動(dòng)的時(shí)候隱藏navigationBar
navigationController.hidesBarsOnSwipe = Yes
  • 設(shè)置navigationBarTitle顏色
UIColor *whiteColor=[UIColor whiteColor];
NSDictionary *dic=[NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];
  • 設(shè)置navigation為透明而不是毛玻璃效果
[self.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
  • 導(dǎo)航欄返回按鈕只保留箭頭,去掉文字
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

4.UITableview

  • 去掉多余的cell分割線
self.tableView.tableFooterView = [[UIView alloc] init];
  • cell分割線頂格顯示
// iOS7以前有效
self.tableView.separatorInset=UIEdgeInsetsZero;
// separatorInset屬性在iOS7之后失效
/**
*  分割線頂格
*/
- (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];
    }
}
  • 動(dòng)態(tài)計(jì)算cellLabel高度
self.tableView.estimatedRowHeight=44.0;
self.tableView.rowHeight=UITableViewAutomaticDimension;
//需要設(shè)置label.numberOfLines = 0
  • cell點(diǎn)擊展開、合起
// 比起[tableView reloadData]刷新方法,[tableView beginUpdates]、[tableView endUpdates],動(dòng)畫效果更好
[tableView beginUpdates];
if(label.numberOfLines==0) {
label.numberOfLines=1;
}else{
label.numberOfLines=0;
}
[tableView endUpdates];
  • 修改cell中小對(duì)勾的顏色
self.tableView.tintColor = [UIColor redColor];

5.UIScrollView

  • scrollView不能滑到頂部
self.automaticallyAdjustsScrollViewInsets = NO;

6.像message app一樣滑動(dòng)時(shí)讓鍵盤消失

適用于textView、scrollView等
可設(shè)置UIScrollViewKeyboardDismissMode枚舉

typedef NS_ENUM(NSInteger,UIScrollViewKeyboardDismissMode){
UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag,// dismisses the keyboard when a drag begins
UIScrollViewKeyboardDismissModeInteractive,// the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
}NS_ENUM_AVAILABLE_IOS(7_0);

在xib中設(shè)置


7.status bar(狀態(tài)欄)

  • 修改狀態(tài)欄文字顏色
[application setStatusBarStyle:UIStatusBarStyleLightContent];
  • 加載啟動(dòng)圖隱藏狀態(tài)欄
    在info.plist文件中設(shè)置


  • 設(shè)置狀態(tài)欄顏色
// 如果沒有navigation bar, 直接設(shè)置 
// make status bar background color
self.view.backgroundColor = COLOR_APP_MAIN;
// 如果有navigation bar, 在navigation bar 添加一個(gè)view來設(shè)置顏色。
// status bar color
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];
[view setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar addSubview:view];

8.Attempt to set a non-property-list object

使用NSUserdefault存儲(chǔ)自定義model時(shí)需要進(jìn)行歸檔,否則會(huì)報(bào)以上錯(cuò)誤

@interface AppointModel :NSObject<NSCoding>
//歸檔
-(void)encodeWithCoder:(NSCoder *)aCoder{
   [aCoder encodeObject:_userid forKey:@"userid"];
   [aCoder encodeObject:_username forKey:@"username"];
}
//解檔
-(id)initWithCoder:(NSCoder *)aDecoder{
   if(self = [super init]) {
      _userid= [aDecoder decodeObjectForKey:@"userid"];
      _username= [aDecoder decodeObjectForKey:@"username"];
   }
   return self;
}

// 轉(zhuǎn)化成NSData
NSData *appointData = [NSKeyedArchiver archivedDataWithRootObject:appointModel];
NSDictionary *dicAppoint = [NSDictionary dictionaryWithObject:appointData forKey:@"canSelectAppoint"];

// 提取
NSData *appointData = [replyInfo objectForKey:@"canSelectAppoint"];
appointModel= [NSKeyedUnarchiver unarchiveObjectWithData:appointData];
//建議使用runtime獲取全部屬性值,方便后續(xù)增加屬性
//歸檔
-(void)encodeWithCoder:(NSCoder *)aCoder{
    unsigned int count;
    Ivar *ivar = class_copyIvarList([AppointModel class], &count);
    for (int i=0; i<count; i++) {
        Ivar iv = ivar[i];
        const char *name = ivar_getName(iv);
        NSString *strName = [NSString stringWithUTF8String:name];
        //利用KVC取值
        id value = [self valueForKey:strName];
        [encoder encodeObject:value forKey:strName];
    }
}
//解檔
-(id)initWithCoder:(NSCoder *)aDecoder{
    if(self = [super init]){
        unsigned int count = 0;
        //獲取類中所有成員變量名
        Ivar *ivar = class_copyIvarList([MyModel class], &count);
        for (int i = 0; i<count; i++) {
            Ivar iv = ivar[i];
            const char *name = ivar_getName(iva);
            NSString *strName = [NSString stringWithUTF8String:name];
            //進(jìn)行解檔取值
            id value = [decoder decodeObjectForKey:strName];
            //利用KVC對(duì)屬性賦值
            [self setValue:value forKey:strName];
        }
    }
    return self;
}

9.NSUserDefaults存儲(chǔ)路徑

NSHomeDirectory()路徑下的/Library/Preferences

例:/Users/zhoumo/Library/Developer/CoreSimulator/Devices/CADC5E86-23AD-4314-883D-C3B86F067B8F/data/Containers/Data/Application/22005060-FCD3-4B95-8A70-69C1063595A3/Library/Preferences

10.文件夾的可讀可寫性

#warning 模擬器可讀可寫,真機(jī)只可讀不可寫
NSString*bundledPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"images"];
// 模擬器路徑
/Users/zm/Library/Developer/CoreSimulator/Devices/81BE0B59-774D-44A1-BF69-E88BF24D39CA/data/Containers/Bundle/Application/C5E5B65E-1BB1-4797-A37C-DDB375045DE1/BusinessFamilyV2.app/images
// 真機(jī)、模擬器可讀可寫
NSString*documentPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Web"];
// 模擬器路徑
/Users/zm/Library/Developer/CoreSimulator/Devices/81BE0B59-774D-44A1-BF69-E88BF24D39CA/data/Containers/Data/Application/102C498F-38F5-49AA-9F58-5D6B4E80FF52/Documents/Web

11.修改UITextField的placeholder的字體顏色、大小、位置

self.textField.placeholder=@"username is in here!";
// 字體顏色
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
// 字體大小
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
// 位置:重寫drawPlaceholderInRect方法
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill]; //也可修改顏色、字體
[self.placeholder drawInRect:rect withFont:[UIFont systemFontOfSize:20]  lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}

12.iOS版本號(hào),Version和Build

Version, 通常說的版本號(hào), 是應(yīng)用向用戶宣傳說明時(shí)候用到的標(biāo)識(shí). 一般有2段或者3段式, 如:2.1,8.1.2。
Build , 編譯號(hào)指一次唯一編譯標(biāo)識(shí), 通常是一個(gè)遞增整數(shù)(安卓強(qiáng)制為數(shù)字, iOS 可以是字符串)。


// 獲取方法
NSDictionary*info=[[NSBundle mainBundle] infoDictionary];

info[@"CFBundleShortVersionString"];//Versioninfo

[@"CFBundleVersion"];// Build

13.加載.png或.JPG格式圖片

// .png格式不需要加后綴
UIImage *pngImage = [UIImage imageNamed:@"myPng"];
// .JPG格式必須加后綴才能顯示
UIImage *jpgImage = [UIImage imageNamed:@"myJPG.JPG"];

#warning 使用xcode插件KSImageNamed的需要注意,插件并不會(huì)自動(dòng)加上后綴,如果是JPG格式依靠插件可能會(huì)導(dǎo)致無法顯示圖片

14.TabBar移除頂部陰影

[[UITabBar appearance]setShadowImage:[[UIImage alloc]init]];

[[UITabBar appearance]setBackgroundImage:[[UIImage alloc]init]];

15.把顏色轉(zhuǎn)成圖片

+ (UIImage*)imageWithColor:(UIColor*)color{

CGRect rect =CGRectMake(0.0f,0.0f,1.0f,1.0f);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context =UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [colorCGColor]);

CGContextFillRect(context, rect);

UIImage *theImage =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return theImage;

}

16.漢字轉(zhuǎn)拼音

// 自定義模型類staffModel
NSMutableString *source = [staffmodel.name mutableCopy];               
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO); 
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
staffmodel.namePinYin = [source lowercaseString];

// 使用自帶排序功能
//staffModel中定義叫做namePinYin的屬性
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"namePinYin" ascending:YES]]; // namePinYin按照屬性排序
[newArray sortUsingDescriptors:sortDescriptors];

17.Block循環(huán)遍歷字典

NSDictionary *dic = @{@"key1":@"value1",@"key2":@"value2"};
// 使用系統(tǒng)自定義block,更加簡潔、高效
方法1:
[dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if([key isEqualToString:@"key1"]){
            
        }
    }];

方法2:
typedef NS_OPTIONS(NSUInteger, NSEnumerationOptions) {
    NSEnumerationConcurrent = (1UL << 0),//并發(fā)遍歷
    NSEnumerationReverse = (1UL << 1),//倒序遍歷
};
[dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if([key isEqualToString:@"key2"]){
            NSLog(dic[key]);
        }
    }];

18.判斷網(wǎng)絡(luò)圖片格式

//通過圖片Data數(shù)據(jù)第一個(gè)字節(jié) 來獲取圖片擴(kuò)展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";     
        case 0x47:
            return @"gif";        
        case 0x49:   
        case 0x4D:
            return @"tiff";        
        case 0x52:  
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}

19.給UIView、UILabel設(shè)置圖片

// 1.設(shè)置成背景顏色
UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"];  
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];  
[myView setBackGroundColor:bgColor];
2.
UIImage *image = [UIImage imageNamed:@"yourPicName@2x.png"];  
yourView.layer.contents = (__bridge id)image.CGImage;//設(shè)置顯示的圖片范圍
yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//四個(gè)值在0-1之間,對(duì)應(yīng)的為x,y,width,height。

20.UIView設(shè)置部分圓角

UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];  
view2.backgroundColor = [UIColor redColor];  
[self.view addSubview:view2];  
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view2.bounds;maskLayer.path = maskPath.CGPath;
view2.layer.mask = maskLayer;
//其中,byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight//指定了需要成為圓角的角。
//該參數(shù)是UIRectCorner類型的,可選的值有:* UIRectCornerTopLeft* UIRectCornerTopRight* UIRectCornerBottomLeft* UIRectCornerBottomRight* UIRectCornerAllCorners

20.禁止自動(dòng)鎖屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

21.刪除NSUserDefaults所有記錄

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults { 
  NSUserDefaults * defs = [NSUserDefaults standardUserDefaults]; 
  NSDictionary * dict = [defs dictionaryRepresentation]; 
  for (id key in dict) {
     [defs removeObjectForKey:key];
 }
   [defs synchronize];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1.badgeVaule氣泡提示 2.git終端命令方法> pwd查看全部 >cd>ls >之后桌面找到文件夾內(nèi)容...
    i得深刻方得S閱讀 4,752評(píng)論 1 9
  • 打印View所有子視圖 layoutSubviews調(diào)用的調(diào)用時(shí)機(jī) 當(dāng)視圖第一次顯示的時(shí)候會(huì)被調(diào)用當(dāng)這個(gè)視圖顯示到...
    hyeeyh閱讀 524評(píng)論 0 3
  • 1、禁止手機(jī)睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa閱讀 1,144評(píng)論 1 6
  • 材料: 吐司片、番茄醬、馬蘇里拉芝士、西藍(lán)花或生菜洋蔥等、玉米粒、培根或醬牛肉等熟肉。 制作步驟: 1.西藍(lán)花掰小...
    Lin_Na閱讀 269評(píng)論 0 0
  • 他們說,感情總在聽不到看不到的時(shí)候最強(qiáng)烈。 起初,我不信,后來,想你的時(shí)候,連空氣都是你的味道。 01 當(dāng)說想你都...
    余shisan閱讀 535評(píng)論 2 7