程序员iOS精品文章-实用技巧&博客总结iOS Developer

iOS开发经验总结

2017-07-19  本文已影响94人  KennyHito
个人链接
微信公众号.jpg
目录

1.强制使用系统键盘;
2.去除数组中相同的元素;
3.修改textField的placeholder的字体颜色、大小;
4.获取app缓存大小;
5.获取手机和app信息;
6.当tableView占不满一屏时,去除下边多余的单元格;
7.删除NSUserDefaults所有记录;
8.禁用系统滑动返回功能;
9.UIView背景颜色渐变,圆角阴影,虚线;
10.让手机震动一下;
11.在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花;
12.打开摇一摇功能;
13.导航栏隐藏和显示功能,统一设置导航栏颜色和导航栏字体的颜色;
14.关于iOS自定义返回按钮右滑返回手势失效的解决;
15.苹果系统自带分享功能
16.iOS中文网址路径转换URLEncode;
17.两个库有冲突;运行Xcode后,会打印一堆东西;
18.iOS开发,生成随机数;
19.设置Btn上文字对其方式(例子:左对齐及左边距);
20.实现通知传值;
21.iOS如何将父视图透明,而内容不透明的方法;
22.如何设置label上面的文字显示不同颜色;
23.设置pch文件路径;
24.iOS开发中,压缩图片的方法(2种方式);
25.根据内容更改cell的高度;
26.解决self对象出现循环引用问题;
27.更改UIAlertController中的message和title的文字对齐方式;
28.根据版本号使用对应的方法;
29.iOS 内购的流程如下;

//在AppDelegate中写:
//强制使用系统键盘 >=iOS8
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier{
    if ([extensionPointIdentifier isEqualToString:@"com.apple.keyboard-service"]) {
        return NO;
    }
    return YES;
}
//去除数组中相同的元素
NSArray *oldArr = @[@"12",@"123",@"123"];
NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"====%@====",newArr);
//修改textField的placeholder的字体颜色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font”];
//获取app缓存大小
- (CGFloat)getCachSize {
    NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
    //获取自定义缓存大小
    //用枚举器遍历 一个文件夹的内容
    //1.获取 文件夹枚举器
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
    __block NSUInteger count = 0;
    //2.遍历
    for (NSString *fileName in enumerator) {
        NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        count += fileDict.fileSize;//自定义所有缓存大小
    }
    // 得到是字节  转化为M
    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
    return totalSize;
}
//获取手机和app信息
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"app_Name: %@",app_Name);
// app版本
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"app_Version: %@",app_Version);
// app build版本
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"app_build: %@",app_build);
//手机序列号
NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString];
NSLog(@"手机序列号: %@",identifierNumber);
//手机别名: 用户定义的名称
NSString* userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"手机别名: %@", userPhoneName);
//设备名称
NSString* deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"设备名称: %@",deviceName );
//手机系统版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"手机系统版本: %@", phoneVersion);
//手机型号
NSString* phoneModel = [[UIDevice currentDevice] model];
NSLog(@"手机型号: %@",phoneModel );
//地方型号  (国际化区域名称)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"国际化区域名称: %@",localPhoneModel);
//当tableView占不满一屏时,去除下边多余的单元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
//删除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];
}
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
//禁用系统滑动返回功能
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return NO;
}
//UIView背景颜色渐变
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 100, HitoScreenW-20, 200)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];

// 左上角和右上角添加圆角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;

//为一个view添加虚线边框
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
border.fillColor = nil;
border.lineDashPattern = @[@4, @2];
border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
border.frame = view.bounds;
[view.layer addSublayer:border];
//让手机震动一下
//导入框架#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
//或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//1、打开摇一摇功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
//2、让需要摇动的控制器成为第一响应者
[self becomeFirstResponder];
//3、实现以下方法
// 开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"开始摇动");
}
// 取消摇动
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"取消摇动");
}
// 摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"摇动结束");
}
//隐藏导航栏
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
//去掉黑线 
[self.navigationController.navigationBar setShadowImage:[UIImage new]];

对立的方法:—>
//显示导航栏
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//加上黑线
[self.navigationController.navigationBar setShadowImage:nil];

具体方法实现 : 
#pragma mark -- 将导航栏隐藏
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//隐藏导航栏
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];//去除黑线
}

#pragma mark -- 将导航栏归还原样
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];//显示导航栏
    [self.navigationController.navigationBar setShadowImage:nil];//加上黑线 
}

(统一设置导航栏颜色和导航栏字体的颜色)
self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

//统一设置导航栏样式,文字颜色及其大小
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

[[UINavigationBar appearance]setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];

[[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:20]}];
(关于iOS自定义返回按钮右滑返回手势失效的解决)
self.navigationController.interactivePopGestureRecognizer.delegate=(id)self;
需要导入头文件 : 
#import<Social/Social.h>

//苹果系统自带分享功能
UIActivityViewController *avc = [[UIActivityViewController alloc]initWithActivityItems:@[@"分享内容名称",[NSURL URLWithString:@"[https://github.com/NSLog-YuHaitao/iOSReview](https://github.com/NSLog-YuHaitao/iOSReview)"]] applicationActivities:nil];
[self presentViewController:avc animated:YES completion:nil];

iOS中文网址路径转换URLEncode

//拼接数据请求时,出现汉字的解决办法
NSString* encodedString = [urlStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
两个库有冲突
设置Xcode中Targets选项下有Other linker flags的设置:    -force_load
xcode中后台打印一堆东西,修改办法
OS_ACTIVITY_MODE        disable
获取一个随机整数范围在:[0,100)包括0,不包括100
int x = arc4random() % 100;
设置Btn上文字对其方式(例子:左对齐及左边距)
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
实现通知传值
第二个界面:
 //注册观察者
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(achiveMessage:) name:@"sendMessage" object:nil];

//实现通知方法
-(void)achiveMessage:(NSNotification *)noti{
   
NSDictionary * dic =  noti.userInfo
;
   
//获得消息之后,通知获得之后
    //获取label 给lable赋值
    NSLog(@"%@",dic[@"pass"]);
}
//移除通知

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"sendMessage" object:nil];
}

第一个界面:
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"sendMessage" object:self userInfo:@{@"pass":要传递的东西}];
iOS如何将父视图透明,而内容不透明的方法
self.view.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.7f];
我们只设置了背景是透明的,没有全局的设置view的透明属性,就能使得添加到view的所有子试图保持原来的属性,不会变成透明的
如何设置label上面的文字显示不同颜色
 //label上的文字
NSString * str = [NSString stringWithFormat:@"%d/%lu",i,(unsigned long)_picArr.count];
//label的颜色
label.textColor = [UIColor greenColor];
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:str];
NSRange redRange = NSMakeRange(0, [[noteStr string] rangeOfString:@"/"].location);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
[label setAttributedText:noteStr];
最终样式:      1/4   2/4  等等
设置pch文件路径
$(SRCROOT)/$(PROJECT_NAME)/PrefixHeader.pch
iOS开发中,压缩图片的方法(2种方式)
方法一:
//压缩图片
-(UIImage*)imageWithImageSimple:(UIImage*)images scaledToSize:(CGSize)newSize{
  UIGraphicsBeginImageContext(newSize);
  [images drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}

方法二:
//压缩图片
-(UIImage *)thumbnailFromImage:(UIImage*)image{
  CGSize originImageSize = image.size;
  CGRect newRect = CGRectMake(0, 0, 100, 100);
  UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
  //(原图的宽高做分母,导致大的结果比例更小,做MAX后,ratio*原图长宽得到的值最小是40,最大则比40大,这样的好处是可以让原图在画进40*40的缩略矩形画布时,origin可以取=(缩略矩形长宽减原图长宽*ratio)/2 ,这样可以得到一个可能包含负数的origin,结合缩放的原图长宽size之后,最终原图缩小后的缩略图中央刚好可以对准缩略矩形画布中央)
  float rotio = MAX(newRect.size.width/originImageSize.width, newRect.size.height/originImageSize.height);
  UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:5.0];
  //剪裁上下文
  [path addClip];
  //让image在缩略图居中() 
  CGRect projectRect;
  projectRect.size.width = originImageSize.width* rotio;
  projectRect.size.height = originImageSize.height * rotio;
  projectRect.origin.x= (newRect.size.width- projectRect.size.width) /2;
  projectRect.origin.y= (newRect.size.height- projectRect.size.height) /2;
    //在上下文画图
  [image drawInRect:projectRect];
  UIImage *thumnailImg = UIGraphicsGetImageFromCurrentImageContext();
  //结束绘制图
  UIGraphicsEndImageContext(); 
  return thumnailImg;
}
根据内容更改cell的高度
方法一:
ChatModel *model = _dataArr[indexPath.row];
NSString *content = model.content;
CGSize size = [content boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}context:nil].size;
return size.height + 30;

方法二:
/* 设置UILabel的高度 */
- (CGSize)sizeWithString:(NSString *)string size:(CGSize)size andFont:(int)font{
    //限制最大的宽度和高度
    CGRect rect = [string boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font]}context:nil];
    return rect.size;
}
__weak typeof (self)weakSelf = self;
     为了解决self对象出现循环引用问题,在硬件操作中经常出现最常见的使用场景,在一个block内部,对当前对应的强引用属性操作时,容易出现循环引用的问题,需要使用以上代码修饰在block内部,使用weakSelf替代self,weakSelf在block内部就变成了弱引用,在block外,不影响self的使用,代码正常写即可.

 self在block内部使用时,用weakSelf替换
    __weak typeof(self)weakSelf = self;
更改UIAlertController中的message和title的文字对齐方式:

UIView *subView1 = alert.view.subviews[0];
UIView *subView2 = subView1.subviews[0];
UIView *subView3 = subView2.subviews[0];
UIView *subView4 = subView3.subviews[0];
UIView *subView5 = subView4.subviews[0];
//取title和message:
UILabel *title = subView5.subviews[0];
UILabel *message = subView5.subviews[1];
//然后设置message内容居左:
message.textAlignment = NSTextAlignmentLeft;
title.textAlignment = NSTextAlignmentLeft;
根据版本号使用对应的方法

判断iOS 8.0 以下的方法如下:
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0

#endif

判断iOS 8.0 以上的方法如下:
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0

#endif

iOS 内购的流程如下

1. 程序向服务器发送请求,获得一份产品列表。
2. 服务器返回包含产品标识符的列表。
3. 程序向App Store发送请求,得到产品的信息。
4. App Store返回产品信息。
5. 程序把返回的产品信息显示给用户(App的store界面)
6. 用户选择某个产品
7. 程序向App Store发送支付请求
8. App Store处理支付请求并返回交易完成信息。
9. 程序从信息中获得数据,并发送至服务器。
10. 服务器纪录数据,并进行审(我们的)查。
11. 服务器将数据发给App Store来验证该交易的有效性。
12. App Store对收到的数据进行解析,返回该数据和说明其是否有效的标识。
13. 服务器读取返回的数据,确定用户购买的内容。
14. 服务器将购买的内容传递给程序。
上一篇 下一篇

猜你喜欢

热点阅读