获取window的三种方式(最后一种最靠谱)
UIWindow *window = self.view.window ;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
简述:宏定义的后面没有符号
0.0.Block的使用
(1) 方法调用block
1.在.h里面(建立吧bock)和设置block的方法
typedef void(^BLOCK)(NSString *name);
-(void)setBlock:(BLOCK)block;(在.m属性需要实现)
2.在.m里面进行实现block方法和属性的转换
先利用BLOCK设置一个属性 BLOCK valueBlock;
-(void)setBlock:(BLOCK)block
{
valueBlock = block;
}
3.在点击的调用的方法里面进行调用
valueBlock(这里放一个字符串传到外面);
4.在外面调用
[类的对象 setBlock:^(NSString *name) {
这里进行执行block这个方法
}];
(2) 属性调用block
1.在.h里面设置2个字符串
@property(nonatomic,strong) void(^guwen)(NSString *paGe,NSString *name);
2.在.m里面点击调用
if (self.guwen) {
self.guwen(pageNumber,self.nameLabel.text);
}
3.在外面把值取出来
利用这个类的对象进行调用
累的对象.guwen = ^(NSString *paGe,NSString *name){
在此进行调用传值
};
0.Profile文件的设置
platform :ios,’7.0’
target “JLCardAnimation” do
pod 'AFNetworking', '~> 3.1.0'
pod 'MJExtension', '~> 3.0.13'
pod 'SDWebImage', '~> 3.8.1'
end
1.尺寸的宏定义
宽高的设置
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
尺寸的设置
#define iPhone5AndEarlyDevice (([[UIScreen mainScreen] bounds].size.height*[[UIScreen mainScreen] bounds].size.width <= 320*568)?YES:NO)
#define Iphone6 (([[UIScreen mainScreen] bounds].size.height*[[UIScreen mainScreen] bounds].size.width <= 375*667)?YES:NO)
2.颜色的宏定义
//RGB颜色
#define CWColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
//随机色(和上面的保持 一致)
#define CWRandomColor CWColor(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256))
自定义随机色
#define CWRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]
3.开发模式(名字自己起)
#ifdef DEBUG //处于开发阶段才打印(调试)
#define CWLog(...) NSLog(__VA_ARGS__)
#else //处于发布阶段(没有输出)(发布)
#define CWLog(...)
#endif
4.NSUserDefaults取值,存值
//取值
#define UserDefaultObject(A) [[NSUserDefaults standardUserDefaults]objectForKey:A]
//存值(可变的值不可以存)
#define UserDefaultSetValue(B,C) [[NSUserDefaults standardUserDefaults]setObject:B forKey:C]
//存BOOL值
#define UserDefaultBool(D,E) [[NSUserDefaults standardUserDefaults]setBool:D forKey:E]
5.弱引用
__weak typeof(self) weakSelf = self;
/*
弱引用
*/
#define STWeakSelf __weak typeof(self) weakSelf = self;
6.判断版本是ios7以后版本
#define IOS_CURRENT_VERSION_IOS7 ([[UIDevice currentDevice].systemVersion floatValue] < 7.0 ? NO : YES)
7.打印函数,可以打印所在的函数,行数,以及你要打印的值
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
NSLog(@"==1==%s 2==[Line %d] 3==%@", __PRETTY_FUNCTION__, __LINE__,string);
8.cell高度根据文本来确定(注意字体的大小和外面的保持一致)
CGFloat height =[@"文字的内容" boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:11] forKey:NSFontAttributeName] context:nil].size.height;
9.请求,上拉,下拉刷新
一般都有页码和数组
NSArray *tempArray;
NSMutableArray *dataArray;
@property(nonatomic,assign) int p;
-(void)refreshData
{
self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
self.p = 1;
dataArray = [[NSMutableArray alloc]init];
[HUD showLoadingHUDWithText:@"加载中..." inView:self.view];
//调用网络请求的方法
[self request:1];
}];
self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
self.p ++;
[HUD showLoadingHUDWithText:@"加载中..." inView:self.view];
//调用网络请求的方法
[self request:self.p];
}];
}
10.网络请求
-(void)request:(int)pp
{
self.title = @"酒店";
#define DFTurl @"http://192.168.80.254"
NSString *url = [NSString stringWithFormat:@"%@/jiekou/index.php?g=home&m=index&a=jiudian&p=%d",DFTurl,pp];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
/*
网络数据的请求
*/
[[SXHTTPEngine shareManager]POST:url params:nil success:^(id responseObject) {
DFTLog(@"====%@",responseObject);
tempArray = responseObject[@"data"];
tempArray = [HostelHomeModel mj_objectArrayWithKeyValuesArray:tempArray];
[dataArray addObjectsFromArray:tempArray];
[HUD hideHUD];
/*
刷新主线程
*/
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
/*
上拉下拉刷新的截止
*/
[self.tableView.mj_header endRefreshing];
[self.tableView.mj_footer endRefreshing];
});
} failure:^(NSError *error) {
DFTLog(@"加载失败");
/*
上拉下拉刷新的截止
*/
[self.tableView.mj_header endRefreshing];
[self.tableView.mj_footer endRefreshing];
[HUD showLoadingHUDWithText:@"加载失败"];
[HUD hideHUD];
}];
});
}
11. 设置导航栏文字的颜色以及文字大小(如导航的背景颜色,以及导航栏中间字体的颜色)
/*
设置导航栏文字的颜色以及文字大小(如导航的背景颜色,以及导航栏中间字体的颜色)
[UINavigationBar appearance];
设置Item的样式
[UIBarButtonItem appearance];
*/
//在第一次使用调用一次
+(void)initialize
{
//设置整个项目所有item的主题样式()
UIBarButtonItem *item = [UIBarButtonItem appearance];
//设置普通状态的字体颜色和大小
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:CWColor(123, 123, 123),NSFontAttributeName:[UIFont systemFontOfSize:20]} forState:UIControlStateNormal];
//设置点击的时候颜色和大小
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:CWColor(252, 108, 8),NSFontAttributeName:[UIFont systemFontOfSize:20]} forState:UIControlStateSelected];
}
导航栏上button图片防止被渲染
UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//宽度为负数的固定间距的系统item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];
UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
12 NSData 转化我 string
/*
1.把 NSData 转化我 string
*/
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
/*
2.把string 转化我 NSData
*/
NSData *data = [respondString dataUsingEncoding:NSUTF8StringEncoding]
//NSString转化为NSNumber
NSString *string = @"9000";
NSNumber *number = @([string integerValue]);
NSLog(@"number=%@",number);
//NSNumber转化为NSString
NSString *string1 = [NSString stringWithFormat:@"%@",number];
NSLog(@"string1=%@",string1);
13主线程刷新
<1>.GCD
dispatch_async(dispatch_get_main_queue(), ^{
});
<2>.NSOperation
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
}];
13.改变图片的大小
我们需要传UIImage 和 CGSize 返回的还是UIImage
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)newsize{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(newsize);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(0, 0, newsize.width, newsize.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return scaledImage;
}
14.有关block的使用
这仅仅是调用的展示
@property(strong,nonatomic)void(^agriculturalBtnClick)();
@property(strong,nonatomic)void(^forestryBtnClick)();
@property(strong,nonatomic)void(^AnimalBtnClick)();
-(void)homeBtnClick:(UIButton *)sender
{
switch (sender.tag) {
case 0:{
if (self.agriculturalBtnClick) {
self.agriculturalBtnClick();
}
}break;
case 1:{
if (self.forestryBtnClick) {
self.forestryBtnClick();
}
}break;
case 2:{
if (self.AnimalBtnClick) {
self.AnimalBtnClick();
}
}break;
}
}
/*
下面是对方法的调用(这是cell里面的调用)
*/
cell.agriculturalBtnClick = ^(){
};
cell.forestryBtnClick = ^(){
};
cell.AnimalBtnClick = ^(){
};
15.一个方法的延迟执行(2s之后执行)
[self performSelector:@selector(logInShouYe) withObject:nil afterDelay:2];
16.打电话
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",[user objectForKey:@"电话"]];
UIWebView * callWebview = [[UIWebView alloc] init];
[callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
[self.view addSubview:callWebview];
17.弱引用的使用
__weak typeof(self) Wself = self;
18.UIWebView加载连接
NSURL *url = [NSURL URLWithString:@"http://www.pgyer.com/iHLM"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIWebView *webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[self.view addSubview:webView];
[webView loadRequest:request];
19.按钮的点击方法(其实只是缩放率的改变,动画的加载)
按钮的点击放大,其实改变的只是按钮的transform(缩放率)
- 下面以一个button为例
UIButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.liekBtn.frame = CGRectMake(CGRectGetMaxX(self.disLikeBtn.frame)+100 , HEIGHT*0.5, 60, 60);
[self.liekBtn setImage:[UIImage imageNamed:@"likeBtn"] forState:UIControlStateNormal];
[self.liekBtn addTarget:self action:@selector(liek) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.liekBtn];
-(void)liek {
[UIView animateWithDuration:0.5
animations:^{
self.liekBtn.transform = CGAffineTransformMakeScale(1.2, 1.2);
} completion:^(BOOL finished) {
self.liekBtn.transform = CGAffineTransformMakeScale(1, 1);
}];
}
3D放大
对象.transform3D = CATransform3DMakeScale(x, y, z);
按钮的点击放大
20.手势冲突的解决方式
//重写手势的方法 手势会影响 cell的点击
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"])
{
return NO;
}else{
return YES;
}
}
21打电话
挂代理
UIAlertView * alertView2 = [[UIAlertView alloc]initWithTitle:@"全国统一客服热线:4007-114-115" message:nil delegate:self cancelButtonTitle:@"拨打" otherButtonTitles:@"取消", nil];
[alertView2 show];
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
UIWebView*callWebview =[[UIWebView alloc] init] ;
NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel://4007114115"]];
[callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
[self.backScrollView addSubview:callWebview];
return;
}
22.导航栏的颜色
可以设置全局,也可以单独设置
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont systemFontOfSize:20]};
/颜色自己随便设置
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.101 green:0.705 blue:0.652 alpha:1.000];
23.自定义导航控制器上面的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//设置图片的两种状态
//正常
[button setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//选中
[button setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(0, 0, 30, 30);
[button addTarget:self action:@selector(back1) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
24.获取版本号
//获取版本号
NSString *version1 = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
25.相机问题
最近做头像上传功能需要使用系统相册、相机,在调用系统相册、相机发现是英文的系统相簿界面后标题显示“photos”,但是手机语言已经设置显示中文,纠结半天,最终在info.plist设置解决问题。发现在项目的info.plist里面添加Localized resources can be mixed YES(表示是否允许应用程序获取框架库内语言)即可解决这个问题。特此记录下以便以后查看和别人解决问题。
26.两种跳转展示
- 1.中间展示(两种写法)
//第一种方法
1.挂代理
2.在点击的地方调用
UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"全国统一客服热线4007-114-115" message:nil delegate:self cancelButtonTitle:@"拨打" otherButtonTitles:@"取消", nil];
[alertView show];
3.方法调用
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"拨打");
}else if (buttonIndex == 1)
{
NSLog(@"取消");
}
}
//第二种方法(方法里面直接调用:不用挂代理)
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"全国统一客服热线4007-114-115" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"拨打" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"拨打");
}];
UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消");
}];
[alertController addAction:alertAction];
[alertController addAction:alertAction2];
[self presentViewController:alertController animated:YES completion:nil];
- 2.下面展示
//第一种方法
1.第一种挂代理
2.在点击的地方调用
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择", @"拍照", nil];
sheet.actionSheetStyle = UIBarStyleDefault;
[sheet showInView:self.view];
3.方法调用
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"我是从手机选择");
}else if (buttonIndex == 1)
{
NSLog(@"我是拍照");
}
}
//第二种方法(方法里面直接调用:不用挂代理)
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"从手机选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"从手机选择");
}];
UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"拍照");
}];
UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消");
}];
[alertController addAction:alertAction];
[alertController addAction:alertAction1];
[alertController addAction:alertAction2];
[self presentViewController:alertController animated:YES completion:nil];
27.对控件边框的处理(如宽度,颜色)
对象(button,label...).layer.borderColor = [[UIColor blackColor] CGColor];
对象(button,label...).layer.borderWidth = 2.0f;
28.自定义导航栏标题
UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
titleLabel.text = @"登陆";
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = [UIColor blackColor];
titleLabel.font = [UIFont systemFontOfSize:15];
self.navigationItem.titleView = titleLabel;
29.静态变量的含义
static 表示只在此文件里可以访问(防止其他文件访问) const防止别人去改
static NSString *const ID = @"cellID";
30.懒加载的一些知识点
懒加载里面都是用_,但是在外面使用都要用self. 这样才能保证数据的存在性
31.切换UICollectionViewFolowLayout
CwLineLayout 是自定义的layout
if ([self.collectionView.collectionViewLayout isKindOfClass:[CwLineLayout class]]) {
[self.collectionView setCollectionViewLayout:[[UICollectionViewFlowLayout alloc]init] animated:YES];
}else
{
[self.collectionView setCollectionViewLayout:[[CwLineLayout alloc]init] animated:YES];
}
31.删除指定item
/**
* collectionView的点击事件
*/
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//删除模型数据(删除的指定item)
[self.imageArray removeObjectAtIndex:indexPath.item];
//刷新UI(这种方式比全局的好很多)
[collectionView deleteItemsAtIndexPaths:@[indexPath]];
}
32.textField.returnKeyType = UIReturnKeySend;
typedef NS_ENUM(NSInteger, UIReturnKeyType) {
UIReturnKeyDefault,
UIReturnKeyGo,//去往
UIReturnKeyGoogle,
UIReturnKeyJoin,//加入
UIReturnKeyNext,//下一步
UIReturnKeyRoute,
UIReturnKeySearch,//搜索
UIReturnKeySend,//发送
UIReturnKeyYahoo,
UIReturnKeyDone,//完成
UIReturnKeyEmergencyCall,
UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
};
33.下一个tabBar隐藏
testViewController.hidesBottomBarWhenPushed = YES;
34. 判断手机号码格式是否正确,利用正则表达式验证
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
if (mobileNum.length != 11)
{
return NO;
}
/** * 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
* 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
* 联通号段: 130,131,132,155,156,185,186,145,176,1709
* 电信号段: 133,153,180,181,189,177,1700
*/
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$";
/** * 中国移动:China Mobile
* 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
*/
NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(^1705\d{7}$)";
/** * 中国联通:China Unicom
* 130,131,132,155,156,185,186,145,176,1709
*/
NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(^1709\d{7}$)";
/** * 中国电信:China Telecom
* 133,153,180,181,189,177,1700
*/
NSString *CT = @"(^1(33|53|77|8[019])\d{8}$)|(^1700\d{7}$)";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
if (([regextestmobile evaluateWithObject:mobileNum] == YES) || ([regextestcm evaluateWithObject:mobileNum] == YES) || ([regextestct evaluateWithObject:mobileNum] == YES) || ([regextestcu evaluateWithObject:mobileNum] == YES))
{
return YES;
}
else
{
return NO;
}
}
35. 判断邮箱格式是否正确,利用正则表达式验证
+ (BOOL)isAvailableEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}
36. 判断字符串中是否含有空格
+ (BOOL)isHaveSpaceInString:(NSString *)string
{
NSRange _range = [string rangeOfString:@" "];
if (_range.location != NSNotFound)
{
return YES;
}else
{
return NO;
}
}
37. 判断字符串中是否含有中文
+ (BOOL)isHaveChineseInString:(NSString *)string
{
for(NSInteger i = 0; i < [string length]; i++)
{
int a = [string characterAtIndex:i];
if (a > 0x4e00 && a < 0x9fff)
{
return YES;
}
}
return NO;
}
38. 判断字符串是否全部为数字
+ (BOOL)isAllNum:(NSString *)string
{
unichar c;
for (int i=0; i判断是否是纯数字
+ (BOOL)isPureInteger:(NSString *)str {
NSScanner *scanner = [NSScanner scannerWithString:str];
NSInteger val;
return [scanner scanInteger:&val] && [scanner isAtEnd];
}
39. 过滤一些特殊字符 似乎只能去除头尾的特殊字符(不准)
+ (NSString *)filterSpecialWithString:(NSString *)string
{
// 定义一个特殊字符的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: @ "@/:;: ;()?「」"、[]{}#%-*+=_|~<>$?^?'@#$%^&*()_+'"];
// 过滤字符串的特殊字符
NSString *newString = [string stringByTrimmingCharactersInSet:set]; return newString;
}
40. 让iOS应用直接退出
+ (void)backOutApp
{
UIWindow *window = [[UIApplication sharedApplication].delegate window];
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished)
{
exit(0);
}];
}
41 NSArray 快速求总和、最大值、最小值、平均值
+ (NSString *)caculateArray:(NSArray *)array
{
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(@"%fn%fn%fn%f",sum,avg,max,min);
return [NSString stringWithFormat:@"%f",sum];
}
42.生成八位随机字符串(一般是RSA加密或者DES加密使用)
- (NSString *)shuffledAlphabet {
NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Get the characters into a C array for efficient shuffling
NSUInteger numberOfCharacters = [alphabet length];
unichar *characters = calloc(numberOfCharacters, sizeof(unichar));
[alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];
// Perform a Fisher-Yates shuffle
for (NSUInteger i = 0; i < numberOfCharacters; ++i) {
NSUInteger j = (arc4random_uniform((float)numberOfCharacters - i) + i);
unichar c = characters[i];
characters[i] = characters[j];
characters[j] = c;
}
// Turn the result back into a string
NSString *result = [NSString stringWithCharacters:characters length:8];
free(characters);
return result;
}
43.判断是真机还是模拟器
#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
44.GCD 的宏定义
很多小伙伴都非常烦写GCD的方法,所以在此定义为宏使用更加方便简洁!如下图
//GCD - 一次性执行
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//GCD - 在Main线程上运行
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
//GCD - 开启异步线程
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
45.判断当前的iPhone设备/系统版本
//判断是否为iPhone
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
//判断是否为iPad
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//判断是否为ipod
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])
// 判断是否为 iPhone 5SE
#define iPhone5SE [[UIScreen mainScreen] bounds].size.width == 320.0f && [[UIScreen mainScreen] bounds].size.height == 568.0f
// 判断是否为iPhone 6/6s
#define iPhone6_6s [[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 667.0f
// 判断是否为iPhone 6Plus/6sPlus
#define iPhone6Plus_6sPlus [[UIScreen mainScreen] bounds].size.width == 414.0f && [[UIScreen mainScreen] bounds].size.height == 736.0f
//获取系统版本
#define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
//判断 iOS 8 或更高的系统版本
#define IOS_VERSION_8_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))
46.获取当前语言
#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
47.“Info.plist”中将要使用的URL Schemes列为白名单
当你的应用在iOS 9中需要使用 QQ/QQ空间/支付宝/微信SDK 的相关能力(分享、收藏、支付、登录等)时,需要在“Info.plist”里增加如下代码:
LSApplicationQueriesSchemes
wechat
weixin
sinaweibohd
sinaweibo
sinaweibosso
weibosdk
weibosdk2.5
mqqapi
mqq
mqqOpensdkSSoLogin
mqqconnect
mqqopensdkdataline
mqqopensdkgrouptribeshare
mqqopensdkfriend
mqqopensdkapi
mqqopensdkapiV2
mqqopensdkapiV3
mqzoneopensdk
wtloginmqq
wtloginmqq2
mqqwpa
mqzone
mqzonev2
mqzoneshare
wtloginqzone
mqzonewx
mqzoneopensdkapiV2
mqzoneopensdkapi19
mqzoneopensdkapi
mqzoneopensdk
alipay
alipayshare
48.将秒转化为时间字符串
秒数
float currentPlayTime = 64;
//将秒转化为时间字符串
NSString *currentTimeStr = [self convertDuraion:currentPlayTime];
- (NSString *)convertDuraion:(float)duraion{
NSDate *date = [NSDate dateWithTimeIntervalSince1970:duraion];
NSDateFormatter *dateFormate = [[NSDateFormatter alloc]init];
dateFormate.dateFormat = @"mm:ss";
return [dateFormate stringFromDate:date];
}
49.有关字符串
NSString *string1 = @"0123456789";
NSRange range1 = NSMakeRange(1, 4);//NSMakeRange这个函数的作用是从第0位开始计算,长度为4
NSLog(@"从第1个字符开始,长度为4的字符串是:%@",[string1 substringWithRange:range1]);
NSLog(@"抽取从头开始到第4个字符:%@",[string1 substringToIndex:4]);
NSLog(@"抽取从第6个字符开始到末尾:%@",[string1 substringFromIndex:6]);
NSString *string2 = @"wo shi xiao bai zhu";
NSRange range2 = [string2 rangeOfString:@"bai"];
if (range2.length > 0) {
NSLog(@"{字符串中“bai”的位置,长度}==%@",NSStringFromRange(range2));
}
//判断在一串字符串中是否找到某个字符串
NSRange range3 = [string2 rangeOfString:@"zhu"];
if (range3.location != NSNotFound) {
NSLog(@"找到了@“zhu”这个字符串!");
}
else
{
NSLog(@"没找到!");
}
50.交换两个值(异或)
51.角度转弧度
宏定义: #define angle2radion(angle) ((angle) / 180.0 * M_PI)
52.获取当前的系统时间(以日历表为例)
//获取当前日历对象
NSCalendar *calendar =[NSCalendar currentCalendar];
//获取日期的组件,年月日,时分秒
//components: 需要获取日期组件
//formDate:获取哪个日期组件
//经验:以后枚举中有移位运算符(<<),一般来说我们就可以用 | :"并" 的方式
NSDateComponents *dateComponents = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSLog(@"小时==%ld",dateComponents.hour);
NSLog(@"分钟==%ld",dateComponents.minute);
NSLog(@"秒==%ld",dateComponents.second);
53.点转化为对象
[NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(500), arc4random_uniform(500))];
54.隐藏tabBar
控制器对象.hidesBottomBarWhenPushed = YES;(比较好)
55.刷新指定section或者row
//一个section刷新
NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];
[_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//一个cell刷新
NSIndexPath *indexPath1=[NSIndexPath indexPathForRow:3 inSection:0];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1,nil] withRowAnimation:UITableViewRowAnimationNone];
56. 遍历字典
NSDictionary *dict = [NSDictionary new];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// key 是键
// obj 是值
}];
57. NSTimer定时器
创建定时器
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(click1) userInfo:nil repeats:YES];
暂停
[timer setFireDate:[NSDate distantFuture]];
继续
[timer setFireDate:[NSDate date]];
关闭定时器
[timer invalidate];
58.两张图片的合成
/**
* 3.将两个图片合成
*/
dispatch_group_notify(group, queue, ^{
/**
* 开启新的图形上下文
*/
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
//绘制图片
[self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
//绘制图片
[self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
/**
* 取得上下文里面的图片
*/
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
/**
* 结束上下文
*/
UIGraphicsEndImageContext();
/**
* 4.进入主队列加载合成的图片
*/
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
59沙盒路径
//获取整个程序所在目录
NSString *homePath=NSHomeDirectory();
NSLog(@"%@",homePath);
//获取.app文件目录
NSString *appPath=[[NSBundle mainBundle]bundlePath];
NSLog(@"%@",appPath);
//Documents目录
NSArray *arr1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr1 objectAtIndex:0]);
//Library目录
NSArray *arr2=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr2 objectAtIndex:0]);
//Caches目录,在Library下面
NSArray *arr3=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSLog(@"%@",[arr3 objectAtIndex:0]);
//tmp目录
NSString *tmpPath=NSTemporaryDirectory();
NSLog(@"%@",tmpPath);
//用整个程序目录加上tmp就拼凑出tmp目录,其他目录都可这样完成
NSString *tmpPath_1=[homePath stringByAppendingPathComponent:@"tmp"];
NSLog(@"%@",tmpPath_1);
60.几个常用的正则表达式
//邮箱
+ (BOOL) validateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}
//手机号码验证
+ (BOOL) validateMobile:(NSString *)mobile
{
//手机号以13, 15,18开头,八个 \d 数字字符
NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
return [phoneTest evaluateWithObject:mobile];
}
//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo
{
NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
NSLog(@"carTest is %@",carTest);
return [carTest evaluateWithObject:carNo];
}
//车型
+ (BOOL) validateCarType:(NSString *)CarType
{
NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
return [carTest evaluateWithObject:CarType];
}
//用户名
+ (BOOL) validateUserName:(NSString *)name
{
NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
BOOL B = [userNamePredicate evaluateWithObject:name];
return B;
}
//密码
+ (BOOL) validatePassword:(NSString *)passWord
{
NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
return [passWordPredicate evaluateWithObject:passWord];
}
//以下验证不计算长度
//1、验证字符串
- (BOOL)validateNickname:(NSString *)nickname {
// 不包含特殊字符
// 特殊字符包含`、-、=、\、[、]、;、'、,、.、/、~、!、@、#、$、%、^、&、*、(、)、_、+、|、?、>、<、"、:、{、}
NSString *nicknameRegex = @".*[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+.*";
NSPredicate *nicknamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nicknameRegex];
return ![nicknamePredicate evaluateWithObject:nickname];
}
//2、验证密码
- (BOOL)validatePassword:(NSString *)password {
// 特殊字符包含`、-、=、\、[、]、;、'、,、.、/、~、!、@、#、$、%、^、&、*、(、)、_、+、|、?、>、<、"、:、{、}
// 必须包含数字和字母,可以包含上述特殊字符。
// 依次为(如果包含特殊字符)
// 数字 字母 特殊
// 字母 数字 特殊
// 数字 特殊 字母
// 字母 特殊 数字
// 特殊 数字 字母
// 特殊 字母 数字
NSString *passWordRegex = @"(\\d+[a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|([a-zA-Z]+\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|(\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+)|([a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+[a-zA-Z]+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+\\d+)";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
return [passWordPredicate evaluateWithObject:password];
}
//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
return [passWordPredicate evaluateWithObject:nickname];
}
//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
BOOL flag;
if (identityCard.length <= 0) {
flag = NO;
return flag;
}
NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
return [identityCardPredicate evaluateWithObject:identityCard];
}
61.打印方式
NSLog(@"控制器名字=%s 第%d行",__PRETTY_FUNCTION__, __LINE__);
62.控制屏幕旋转,在控制器中写
/** 是否支持自动转屏 */
- (BOOL)shouldAutorotate {
return YES;
}
/** 支持哪些屏幕方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
/** 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法) */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
}
63.几个常用权限判断
if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
NSLog(@"没有定位权限");
}
AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (statusVideo == AVAuthorizationStatusDenied) {
NSLog(@"没有摄像头权限");
}
//是否有麦克风权限
AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (statusAudio == AVAuthorizationStatusDenied) {
NSLog(@"没有录音权限");
}
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusDenied) {
NSLog(@"没有相册权限");
}
}];
64.获取手机和app信息
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow(infoDictionary);
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
// app版本
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
// app build版本
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
//手机序列号
NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
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 );
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 当前应用名称
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"当前应用名称:%@",appCurName);
// 当前应用软件版本 比如:1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"当前应用软件版本:%@",appCurVersion);
// 当前应用版本号码 int类型
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"当前应用版本号码:%@",appCurVersionNum);
65.移除字符串中的空格和换行
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
66.判断字符串中是否有空格
+ (BOOL)isBlank:(NSString *)str {
NSRange _range = [str rangeOfString:@" "];
if (_range.location != NSNotFound) {
//有空格
return YES;
} else {
//没有空格
return NO;
}
}
67.获取一个视频的第一帧图片
NSURL *url = [NSURL URLWithString:filepath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return one;
68.获取视频的时长
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
NSURL *videoUrl = [NSURL URLWithString:urlString];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);
return seconds;
}
69.isKindOfClass和isMemberOfClass的区别
isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。
isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)
70.将tableView滚动到顶部
[tableView setContentOffset:CGPointZero animated:YES];
或者
[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
71.UILabel设置内边距
子类化UILabel,重写drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect {
// 边距,上左下右
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
72.UILabel设置文字描边
子类化UILabel,重写drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
// 设置描边宽度
CGContextSetLineWidth(c, 1);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
// 描边颜色
self.textColor = [UIColor redColor];
[super drawTextInRect:rect];
// 文本颜色
self.textColor = [UIColor yellowColor];
CGContextSetTextDrawingMode(c, kCGTextFill);
[super drawTextInRect:rect];
}
73.scrollView滚动到最下边
CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:YES];
74.UIView背景颜色渐变
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[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];
75.将一个view放置在其兄弟视图的最上面
[parentView bringSubviewToFront:yourView]
76.将一个view放置在其兄弟视图的最下面
[parentView sendSubviewToBack:yourView]
77.让手机震动一下
倒入框架
#import
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
78.layoutSubviews方法什么时候调用?
1、init方法不会调用
2、addSubview方法等时候会调用
3、bounds改变的时候调用
4、scrollView滚动的时候会调用scrollView的
layoutSubviews方法(所以不建议在scrollView的layoutSubviews方法中做复杂逻辑)
5、旋转设备的时候调用
6、子视图被移除的时候调用
79.让UILabel在指定的地方换行
// 换行符为\n,在需要换行的地方加上这个符号即可,如
label.numberOfLines = 0;
label.text = @"此处\n换行";
80.摇一摇功能
1、打开摇一摇功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
2、让需要摇动的控制器成为第一响应者
[self becomeFirstResponder];
3、实现以下方法
// 开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 取消摇动
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
81.获取view的坐标在整个window上的位置
// v上的(0, 0)点在toView上的位置
CGPoint point = [v convertPoint:CGPointMake(0, 0) toView:[UIApplication sharedApplication].windows.lastObject];
或者
CGPoint point = [v.superview convertPoint:v.frame.origin toView:[UIApplication sharedApplication].windows.lastObject];
82.提交App Store审核程序限制
您的应用程序的未压缩大小必须小于4GB。每个Mach-O可执行文件(例如app_name.app/app_name)不能超过这些限制:
对于MinimumOSVersion小于7.0的应用程序:TEXT二进制文件中所有部分的总数最多为80 MB 。
对于MinimumOSVersion7.x到8.x的应用程序:TEXT对于二进制文件中每个体系结构片段的每个片段,最大为60 MB 。
对于MinimumOSVersion9.0或更高版本的应用程序:__TEXT二进制文件中所有部分的总数最多为500 MB 。参阅:iTunes Connect开发者指南
83.修改UISegmentedControl的字体大小
[segment setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} forState:UIControlStateNormal];
84.在非ViewController的地方弹出UIAlertController对话框
// 最好抽成一个分类
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
If([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertController animated:YES completion:nil];
85.获取一个view所属的控制器
// view分类方法
- (UIViewController *)belongViewController {
for (UIView *next = [self superview]; next; next = next.superview) {
UIResponder* nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
86.UIImage和base64互转
// view分类方法
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
87.UIWebView设置背景透明
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
88.判断NSDate是不是今天
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] && [today month] == [otherDay month] &&[today year] == [otherDay year] && [today era] == [otherDay era]) {
// 是今天
}
89.设置tableView分割线颜色
[self.tableView setSeparatorColor:[UIColor myColor]];
90.设置屏幕方向
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
91.UITextView中打开或禁用复制,剪切,选择,全选等功能
// 继承UITextView重写这个方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
// 返回NO为禁用,YES为开启
// 粘贴
if (action == @selector(paste:)) return NO;
// 剪切
if (action == @selector(cut:)) return NO;
// 复制
if (action == @selector(copy:)) return NO;
// 选择
if (action == @selector(select:)) return NO;
// 选中全部
if (action == @selector(selectAll:)) return NO;
// 删
if (action == @selector(delete:)) return NO;
// 分享
if (action == @selector(share)) return NO;
return [super canPerformAction:action withSender:sender];
}
92.屏幕截图
/**
* @brief 屏幕截图
*/
+ (UIImage *)screenShotWithView:(UIView *)v;
+ (UIImage *)screenShotWithView:(UIView *)v;
{
UIGraphicsBeginImageContext(v.frame.size);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
93.获取视频的第一帧图片
-(UIImage *)videoUrl:(NSString *)url{
NSURL *urlString = [NSURL URLWithString:url];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:urlString options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *oneImage = [[UIImage alloc] initWithCGImage:oneRef];
return oneImage;
}