iOS开发小经验总结(持续更新中)

1.iphone尺寸

手机 型号 屏幕尺寸
iPhone 4 4s 320 * 480
iPhone 5 5s 320 * 568
iPhone 6 6s 375 * 667
iPhone 6Plus 6sPlus 414 * 736

2.两个app之间跳转

  1. 在app2的info.plist中定义URL,就是在文件中添加URL types一项。可按下图进行添加。


    iOS开发小经验总结(持续更新中)_第1张图片
  2. 在app1的代码中定义跳转,代码如下:
NSURL *url = [NSURL URLWithString:@"myApp://"];
if ([[UIApplication sharedApplication] canOpenURL:url]){
    [[UIApplication sharedApplication] openURL:url];
}
  1. 打开之后,会调用app2的AppDelegate:
-(BOOL)application:(UIApplication*)app openURL:
(NSURL*)url options:(NSDictionary *)options{
}

3.navigation

  • 自定义leftNavigationBar左滑返回手势失效
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:img 
                                          style:UIBarButtonItemStylePlain 
                                          target:self 
                                          action:@selector(onBack:)];
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
  • 滑动的时候隐藏navigationBar
navigationController.hidesBarsOnSwipe = Yes
  • 设置navigationBarTitle颜色
UIColor *whiteColor=[UIColor whiteColor];
NSDictionary *dic=[NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];
  • 设置navigation为透明而不是毛玻璃效果
[self.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
  • 导航栏返回按钮只保留箭头,去掉文字
[[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];
    }
}
  • 动态计算cellLabel高度
self.tableView.estimatedRowHeight=44.0;
self.tableView.rowHeight=UITableViewAutomaticDimension;
//需要设置label.numberOfLines = 0
  • cell点击展开、合起
// 比起[tableView reloadData]刷新方法,[tableView beginUpdates]、[tableView endUpdates],动画效果更好
[tableView beginUpdates];
if(label.numberOfLines==0) {
label.numberOfLines=1;
}else{
label.numberOfLines=0;
}
[tableView endUpdates];
  • 修改cell中小对勾的颜色
self.tableView.tintColor = [UIColor redColor];

5.UIScrollView

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

6.像message app一样滑动时让键盘消失

适用于textView、scrollView等
可设置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中设置


iOS开发小经验总结(持续更新中)_第2张图片

7.status bar(状态栏)

  • 修改状态栏文字颜色
[application setStatusBarStyle:UIStatusBarStyleLightContent];
  • 加载启动图隐藏状态栏
    在info.plist文件中设置


  • 设置状态栏颜色
// 如果没有navigation bar, 直接设置 
// make status bar background color
self.view.backgroundColor = COLOR_APP_MAIN;
// 如果有navigation bar, 在navigation bar 添加一个view来设置颜色。
// 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存储自定义model时需要进行归档,否则会报以上错误

@interface AppointModel :NSObject
//归档
-(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;
}

// 转化成NSData
NSData *appointData = [NSKeyedArchiver archivedDataWithRootObject:appointModel];
NSDictionary *dicAppoint = [NSDictionary dictionaryWithObject:appointData forKey:@"canSelectAppoint"];

// 提取
NSData *appointData = [replyInfo objectForKey:@"canSelectAppoint"];
appointModel= [NSKeyedUnarchiver unarchiveObjectWithData:appointData];
//建议使用runtime获取全部属性值,方便后续增加属性
//归档
-(void)encodeWithCoder:(NSCoder *)aCoder{
    unsigned int count;
    Ivar *ivar = class_copyIvarList([AppointModel class], &count);
    for (int i=0; i

9.NSUserDefaults存储路径

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 模拟器可读可写,真机只可读不可写
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
// 真机、模拟器可读可写
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版本号,Version和Build

Version, 通常说的版本号, 是应用向用户宣传说明时候用到的标识. 一般有2段或者3段式, 如:2.1,8.1.2。
Build , 编译号指一次唯一编译标识, 通常是一个递增整数(安卓强制为数字, iOS 可以是字符串)。


iOS开发小经验总结(持续更新中)_第3张图片
// 获取方法
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的需要注意,插件并不会自动加上后缀,如果是JPG格式依靠插件可能会导致无法显示图片

14.TabBar移除顶部阴影

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

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

15.把颜色转成图片

+ (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.汉字转拼音

// 自定义模型类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循环遍历字典

NSDictionary *dic = @{@"key1":@"value1",@"key2":@"value2"};
// 使用系统自定义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),//并发遍历
    NSEnumerationReverse = (1UL << 1),//倒序遍历
};
[dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if([key isEqualToString:@"key2"]){
            NSLog(dic[key]);
        }
    }];

18.判断网络图片格式

//通过图片Data数据第一个字节 来获取图片扩展名
- (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设置图片

// 1.设置成背景颜色
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:@"[email protected]"];  
yourView.layer.contents = (__bridge id)image.CGImage;//设置显示的图片范围
yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//四个值在0-1之间,对应的为x,y,width,height。

20.UIView设置部分圆角

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//指定了需要成为圆角的角。
//该参数是UIRectCorner类型的,可选的值有:* UIRectCornerTopLeft* UIRectCornerTopRight* UIRectCornerBottomLeft* UIRectCornerBottomRight* UIRectCornerAllCorners

20.禁止自动锁屏

[[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];
}

你可能感兴趣的:(iOS开发小经验总结(持续更新中))