iOS 知识-常用小技巧大杂烩

2016-11-10  本文已影响70人  好少年

版权声明:本文为博主原创文章,未经博主授权不得转载。
开发过程中遇到的一些问题

网上查阅整理的一些问题

供大家参考,方便大家查阅

  1. 打印View所有子视图

po [[self view]recursiveDescription]

  1. layoutSubviews调用的调用时机
  1. NSString过滤特殊字符

// 定义一个特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-
+=\|~<>$ۥ'@#$%&*()+'""];
// 过滤字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];

  1. TransForm属性

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

//旋转按钮
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);

//缩放按钮
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化复位
self.buttonView.transform = CGAffineTransformIdentity;

  1. 去掉分割线多余15像素

首先在viewDidLoad方法加入以下代码:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
然后在重写willDisplayCell方法

  1. 计算方法耗时时间间隔

// 获取时间间隔

define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

  1. 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)]

  1. Alert提示宏定义

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

  1. 让iOS应用直接退出
  1. NSArray 快速求总和 最大值 最小值 和 平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

  1. 修改Label中不同文字颜色
  1. 播放声音

import<AVFoundation>

// 1.获取音效资源的路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
// 2.将路劲转化为url
NSURL *tempUrl = [NSURL fileURLWithPath:path];
// 3.用转化成的url创建一个播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self.player = play;
// 4.播放
[play play];

  1. 检测是否IPad Pro
  1. Label行间距

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

//调整行间距       

[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}

  1. UIImageView填充模式

@"UIViewContentModeScaleToFill", // 拉伸自适应填满整个视图
@"UIViewContentModeScaleAspectFit", // 自适应比例大小显示
@"UIViewContentModeScaleAspectFill", // 原始大小显示
@"UIViewContentModeRedraw", // 尺寸改变时重绘
@"UIViewContentModeCenter", // 中间
@"UIViewContentModeTop", // 顶部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中间贴左
@"UIViewContentModeRight", // 中间贴右
@"UIViewContentModeTopLeft", // 贴左上
@"UIViewContentModeTopRight", // 贴右上
@"UIViewContentModeBottomLeft", // 贴左下
@"UIViewContentModeBottomRight", // 贴右下

  1. 宏定义检测block是否可用

define BLOCK_EXEC(block, ...) if (block) { block(VA_ARGS); };

// 宏定义之前的用法
if (completionBlock) {
completionBlock(arg1, arg2);
}
// 宏定义之后的用法
BLOCK_EXEC(completionBlock, arg1, arg2);

  1. Debug栏打印时自动把Unicode编码转化成汉字

// 有时候我们在xcode中打印中文,会打印出Unicode编码,还需要自己去一些在线网站转换,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin 插件

  1. 设置状态栏文字样式颜色

[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

  1. 自动生成模型代码的插件

// 可自动生成模型的代码,省去写模型代码的时间
ESJsonFormat-for-Xcode

  1. iOS中的一些手势

轻击手势(TapGestureRecognizer)
轻扫手势(SwipeGestureRecognizer)
长按手势(LongPressGestureRecognizer)
拖动手势(PanGestureRecognizer)
捏合手势(PinchGestureRecognizer)
旋转手势(RotationGestureRecognizer)

  1. 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/Provisioning Profiles

  1. 获取 iOS 路径的方法

获取家目录路径的函数
NSString *homeDir = NSHomeDirectory();

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();

  1. 字符串相关操作

去除所有的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]

去除首尾的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

  1. CocoaPods pod install/pod update更新慢的问题

pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。

  1. MRC和ARC混编设置方式

在XCode中targets的build phases选项下Compile Sources下选择 不需要arc编译的文件
双击输入 -fno-objc-arc 即可

MRC工程中也可以使用ARC的类,方法如下:
在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件
双击输入 -fobjc-arc 即可

  1. 把tableview里cell的小对勾的颜色改成别的颜色

_mTableView.tintColor = [UIColor redColor];

  1. 调整tableview的separaLine线的位置

tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

  1. 设置滑动的时候隐藏navigationbar

navigationController.hidesBarsOnSwipe = Yes

  1. 自动处理键盘事件,实现输入框防遮挡的插件

IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager

  1. Quartz2D相关

图形上下是一个CGContextRef类型的数据。
图形上下文包含:
1,绘图路径(各种各样图形)
2,绘图状态(颜色,线宽,样式,旋转,缩放,平移)
3,输出目标(绘制到什么地方去?UIView、图片)

1,获取当前图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
2,添加线条
CGContextMoveToPoint(ctx, 20, 20);
3,渲染
CGContextStrokePath(ctx);
CGContextFillPath(ctx);
4,关闭路径
CGContextClosePath(ctx);
5,画矩形
CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120));
6,设置线条颜色
[[UIColor redColor] setStroke];
7, 设置线条宽度
CGContextSetLineWidth(ctx, 20);
8,设置头尾样式
CGContextSetLineCap(ctx, kCGLineCapSquare);
9,设置转折点样式
CGContextSetLineJoin(ctx, kCGLineJoinBevel);
10,画圆
CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100));
11,指定圆心
CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1);
12,获取图片上下文
UIGraphicsGetImageFromCurrentImageContext();
13,保存图形上下文
CGContextSaveGState(ctx)
14,恢复图形上下文
CGContextRestoreGState(ctx)

  1. 屏幕截图

    // 1. 开启一个与图片相关的图形上下文
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

    // 2. 获取当前图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 3. 获取需要截取的view的layer
    [self.view.layer renderInContext:ctx];

    // 4. 从当前上下文中获取图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 5. 关闭图形上下文
    UIGraphicsEndImageContext();

    // 6. 把图片保存到相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

  2. 隐藏导航栏上的返回字体

//Swift
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)
//OC
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

  1. 解决tableview的分割线短一截

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

  1. 动态隐藏NavigationBar

//1.当我们的手离开屏幕时候隐藏

  1. 设置导航栏透明

//方法一:设置透明度
[[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1];
//方法二:设置背景图片
/**

*/

  1. 设置字体和行间距

//设置字体和行间距
UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)];
lable.text = @"大家好,我是Frank_chun,在这里我们一起学习新的知识,总结我们遇到的那些坑,共同的学习,共同的进步,共同的努力,只为美好的明天!!!有问题一起相互的探讨--438637472!!!";
lable.numberOfLines = 0;
lable.font = [UIFont systemFontOfSize:12];
lable.backgroundColor = [UIColor grayColor];
[self.view addSubview:lable];
//设置每个字体之间的间距
//NSKernAttributeName 这个对象所对应的值是一个NSNumber对象(包含小数),作用是修改默认字体之间的距离调整,值为0的话表示字距调整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];
//设置某写字体的颜色
//NSForegroundColorAttributeName 设置字体颜色
NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange];
NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length);
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];
//设置每行之间的间距
//NSParagraphStyleAttributeName 设置段落的样式
NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init];
[par setLineSpacing:20];
//为某一范围内文字添加某个属性
//NSMakeRange表示所要的范围,从0到整个文本的长度
[str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];
效果图

  1. 点击button倒计时

//第一种方法
//点击button倒计时

import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIButton * timeButton;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong)UIButton * btn;
@end@implementation ViewController
{
NSInteger _time;
}

pragma mark -点击发送验证码

  1. UITextField默认占位符是居中显示,让其居上显示

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

  1. 解决同时按两个按钮进两个view的问题

[button setExclusiveTouch:YES];

  1. 图片拉伸

UIImage* img=[UIImage imageNamed:@"2.png"];//原图
UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10);
//UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
//UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图
img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch];
self.imageView.image=img;

  1. 修改textFieldplaceholder字体颜色和大小

textField.placeholder = @"username is in here!";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

  1. 修改状态栏字体颜色

只能设置两种颜色,黑色和白色,系统默认黑色
设置为白色方法:
(1)在plist里面添加Status bar style,值为UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)
(2)在Info.plist中设置UIViewControllerBasedStatusBarAppearance 为NO

  1. 去掉导航栏下边的黑线

[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

  1. 修改pagecontrol颜色

_pageControl.currentPageIndicatorTintColor=SFQRedColor;
_pageControl.pageIndicatorTintColor=SFQGrayColor;

  1. 去掉UITableView的section的粘性,使其不会悬停

//有时候使用UITableView所实现的列表,会使用到section,但是又不希望它粘在最顶上而是跟随滚动而消失或者出现

  1. 通过2D仿射函数实现小的动画效果(变大缩小) --可用于自定义pageControl中

[UIView animateWithDuration:0.3 animations:^{
imageView.transform = CGAffineTransformMakeScale(2, 2);
} completion:^(BOOL finished) {
imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
}];

  1. UIImage与字符串互转

//图片转字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image
{
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
return encodedImageStr;
}

//字符串转图片
-(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
return _decodedImage;
}

  1. 判断NSString中是否包含中文

-(BOOL)isChinese:(NSString *)str{
NSString *match=@"(^[\u4e00-\u9fa5]+$)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
return [predicate evaluateWithObject:str];
}

  1. NSDate与NSString的相互转化

-(NSString *)dateToString:(NSDate *)date {
// 初始化时间格式控制器
NSDateFormatter *matter = [[NSDateFormatter alloc] init];
// 设置设计格式
[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
// 进行转换
NSString *dateStr = [matter stringFromDate:date];
return dateStr;
}
-(NSDate *)stringToDate:(NSString *)dateStr {

// 初始化时间格式控制器
NSDateFormatter *matter = [[NSDateFormatter alloc] init];
// 设置设计格式
[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
// 进行转换
NSDate *date = [matter dateFromString:dateStr];
return date;
}
以上整理只为自己和大家方便查看,iOS中小技巧不计其数 如果大家有不错的代码和技巧,也可留言或私信我,然后加上, 持续更新中。。。。

上一篇 下一篇

猜你喜欢

热点阅读