1.不常用的属性
//取消自动布局
self.automaticallyAdjustsScrollViewInsets = NO;
//解决tabbar挡住最后一行问题
self.edgesForExtendedLayout = UIRectEdgeNone;
//隐藏cell线
self.tableView.separatorStyle = UITableViewCellSeparateStyleNone;
//push到下个页面需要隐藏tabBar时
svc.hidesBottomBarWhenPushed=YES;
//多余cell空白
self.tableView.tableFooterView = [[UIView alloc]init];
//不超过屏幕也能滑
self.ShowCollection.alwaysBounceVertical = YES;
//选中cell 无背景色
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//推时隐藏tabbar
self.hidesBottomBarWhenPushed = YES;
//button文字靠右
[_button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
//button文字靠左
[_button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
2.解决时差问题
//解决时差问题
NSDate * date = sender.date;
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
//时差转化
NSDate *datenow = [NSDate date];//输出结果:2014-12-12 02:23:25 +0000晚八个小时
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:datenow];
NSDate *localeDate = [datenow dateByAddingTimeInterval: interval];//2014-12-12 10:23:25 +0000
NSLog(@"%@", localeDate);
//将秒数转化为日期格式
NSDate *confromTimesp = [NSDatedateWithTimeIntervalSince1970:1363948516];
NSLog(@"1363948516 = %@",confromTimesp);//2013-03-22 10:35:16 +0000
//将秒数转化为特定格式的日期格式
NSString *str=@"1368082020";//时间戳
NSTimeInterval time=[str doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
NSLog(@"date:%@",[detaildate description]);
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
//最终版本
NSString * startStr = [NSStringstringWithFormat:@"%@",dic[@"startdate"]];
NSTimeInterval startTime = [startStr doubleValue] / 1000 + 28800;
NSDate * startLocalDate = [NSDatedateWithTimeIntervalSince1970:startTime];
NSDateFormatter * startFormatter = [[NSDateFormatter alloc]init];
[startFormatter setDateFormat:@"yyyy.MM.dd"];
NSString * startDate = [startFormatter stringFromDate:startLocalDate];
3.页面切换水波纹动画
DetailViewController * dvc = [[DetailViewControlleralloc]initWithSid:self.dataArray[indexPath.row] [@"secid"]WithCollectorsCount:[self.dataArray[indexPath.row][@"collectcnt"]intValue]];
dvc.hidesBottomBarWhenPushed = YES;
CATransition*transition=[CATransition animation];
transition.duration=1.0f;
transition.type=@"rippleEffect";
transition.subtype=@"fromTop";
[self.navigationController.view.layer addAnimation:transitionforKey:nil];
[self.navigationController pushViewController:dvc animated:YES];
4.去掉导航条和tabBar的边框
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController.navigationBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.navigationController.navigationBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.tabBarController.tabBar setBackgroundImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
[self.tabBarController.tabBar setShadowImage:[TDUtils createImageWithColor:[UIColor clearColor]]];
}
5.导航条多按钮
NSArray *buttonArray = [[NSArray alloc]initWithObjects:cleanButton,saveButton, nil];
self.navigationItem.rightBarButtonItems = buttonArray;
6.真机测试时出现的问题
No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=armv7, VA
运行报错
出现的原因:armv7s是应用在iPhone 5 A6 的架构上的
解决的方式:
1,在Project target里“Architectures”设置为“Standard (armv7,armv7s)”
2,修改在Project target里“Build Settings”的“Valid Architectures”添加“i386”和“armv7”(Xcode4.6 以上版本不再支持armv6,请去掉)
3,设置”Build Active Architecture Only”为“NO”。这样你build你的项目的时候就能在iphoe5和iphoe4s里执行。
7.datepicker修改为中文
方法一
[datePicker setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
方法二
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文显示3
_datePicker.locale = locale;
8.设置属性字体
NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];
[ps setLineHeightMultiple:lineHeight];//行高 [ps setLineSpacing:lineHeight];//行间距
ps.lineBreakMode = NSLineBreakByTruncatingTail;//末尾省略号
ps.lineHeightMultiple = TextLineHeight; //行间距
NSMutableDictionary *attributesDic= [NSMutableDictionary dictionary];
attributesDic[NSForegroundColorAttributeName] = stringColor;
attributesDic[NSFontAttributeName] = stringFont;
attributesDic[NSKernAttributeName] = @(0.5);//字间距
attributesDic[NSParagraphStyleAttributeName] = ps;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:string attributes:attributesDic];
9.屏幕不允许旋转的方法是什么?
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskPortrait;
}
10.电池状态栏改变颜色
方法一:不用修改plist
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
默认的黑色(UIStatusBarStyleDefault)
白色(UIStatusBarStyleLightContent)
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
方法二:需要修改plist
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
/ 设置状态栏字体颜色中国移动的颜色改为白色(需要设置plist文件里的View controller-based status bar appearance属性为NO;)
[UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
//隐藏项目中得状态栏
[[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
info.plist文件中
Status bar is initially hidden yes
View controller-based status bar appearance NO
11.通过抖动的方式提示用户textField文本输入框的text值为空或错误
//TextField的晃动:Begin
@interface UITextField(shake)
- (void)shake;
@end
@implementation UITextField(shake)
- (void)shake
{
CAKeyframeAnimation *animationKey = [CAKeyframeAnimationanimationWithKeyPath:@"position"];
[animationKey setDuration:0.5f];
NSArray *array = [[NSArrayalloc] initWithObjects:
[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
nil];
[animationKey setValues:array];
[array release];
NSArray *times = [[NSArrayalloc] initWithObjects:
[NSNumbernumberWithFloat:0.1f],
[NSNumbernumberWithFloat:0.2f],
[NSNumbernumberWithFloat:0.3f],
[NSNumbernumberWithFloat:0.4f],
[NSNumbernumberWithFloat:0.5f],
[NSNumbernumberWithFloat:0.6f],
[NSNumbernumberWithFloat:0.7f],
[NSNumbernumberWithFloat:0.8f],
[NSNumbernumberWithFloat:0.9f],
[NSNumbernumberWithFloat:1.0f],
nil];
[animationKey setKeyTimes:times];
[times release];
[self.layeraddAnimation:animationKey forKey:@"TextFieldShake"];
}
@end
//TextField的晃动:End
12.二维码图片中间添加logo
+(UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2
{
UIGraphicsBeginImageContext(image1.size);
//Draw image1
[image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
//Draw image2
[image2 drawInRect:CGRectMake((image1.size.width - 60)/ 2, (image1.size.height - 60)/2, 60, 60)];
UIImage *resultImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
13.定义枚举的几种方法
方法一
typedef NS_ENUM(NSInteger, enumCellButtonIndex)
{
eCBIFirst,
eCBISecond,
};
方法二
typedef enum {
commonTag,
differentTag,
noCommonTag
}SortedTag;
方法三
typedef enum : NSUInteger {
eQDTabViewTypeTop,
eQDTabViewTypeBottom,
eQDTabViewTypeBottomHideBar
} QDTabViewType;
14.KVO解决特殊字段(与关键词一样的敏感词)
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"id"]) {
self.ID = value;
}
}
15.TabBar上添加消息提示小红点
1\. 如果有数字,直接使用 viewController.tabBarItem.badgeValue = @"1";
2\. 没有数字,自己往tabbar加subView。
需要注意的是坐标x,y一定要是整数,否则会有模糊。
UIImageView *dotImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"[email protected]"]];
dotImage.backgroundColor = [UIColor clearColor];
dotImage.tag = RED_DOT_TAG;
CGRect tabFrame = tabbarController.tabBar.frame;
CGFloat x = ceilf(0.94 * tabFrame.size.width);
CGFloat y = ceilf(0.2 * tabFrame.size.height);
dotImage.frame = CGRectMake(x, y, 6, 6);
[tabbarController.tabBar addSubview:dotImage];
[dotImage release];
16.让程序在后台较长久的运行
// AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self beingBackgroundUpdateTask];
// 在这里加上你需要长久运行的代码
[self endBackgroundUpdateTask];
}
- (void)beingBackgroundUpdateTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void)endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
17.几种小的概念和方法
1、sleep
[NSThread sleepForTimeInterval:4];
2、活动指示器控件
UIActivityIndicatorView
3、 _cmd的使用
_cmd是iOS内置变量,始终指向当前方法的selector
4、状态加入事件通知中心
[center addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
5、用NSUserDefault保存用户数据
使用方法:
保存:
NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex; [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex forKey:@"selectedIndex"];
取出:
NSNumber *indexNumber = indexNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedIndex"]; if (indexNumber) { NSInteger selectedIndex = [indexNumber intValue]; self.segmentedControl.selectedSegmentIndex = selectedIndex;}
18.有三种方式可以引入静态库文件
第一种方式:直接将对应平台的.a文件拖拽至Xcode工程左侧的Groups&Files中,缺点是每次在真机和模拟器编译时都需要重新添加.a文件;
第二种方式:使用lipo命令将设备和模拟器的.a合并成一个通用的.a文件,将合并后的通用.a文件拖拽至工程中即可,具体命令如下: lipo -create Release-iphoneos/libbaidumapapi.a Release-iphonesimulator/libbaidumapapi.a -output libbaidumapapi.a
第三种方式:
1\. 将API的libs文件夹拷贝到您的Application工程根目录下
2\. 在Xcode的Project -> Edit Active Target -> Build -> Linking -> Other Linker Flags中添加-ObjC
3\. 设置静态库的链接路径,在Xcode的Project -> Edit Active Target -> Build -> Search Path -> Library Search Paths中添加您的静态库目录,比如"$(SRCROOT)/../libs/Release$(EFFECTIVE_PLATFORM_NAME)",$(SRCROOT)宏代表您的工程文件目录,$(EFFECTIVE_PLATFORM_NAME)宏代表当前配置是OS还是simulator
注:静态库中采用ObjectC++实现,因此需要您保证您工程中至少有一个.mm后缀的源文件(您可以将任意一个.m后缀的文件改名为.mm),或者在工程属性中指定编译方式,即将Xcode的Project -> Edit Active Target -> Build -> GCC4.2 - Language -> Compile Sources As设置为"Objective-C++"
19.SDWebImage清除缓存
清除缓存:
[[SDImageCache sharedImageCache] clearDisk];
[[SDImageCache sharedImageCache] clearMemory];
20.view加阴影
view.layer.shadowOpacity = 0.5;// 阴影透明度
view.layer.shadowColor = [UIColor grayColor].CGColor;// 阴影的颜色
view.layer.shadowRadius = 3;// 阴影扩散的范围控制
view.layer.shadowOffset = CGSizeMake(1, 1);// 阴影的范围
21.将view加到UIWindow上
UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:drawView];
_drawView = drawView;
22.AES加密解密。
// NSData+AES256.h
#import
#import
#import
@interface NSData(AES256)
- (NSData *)aes256_encrypt:(NSString *)key;
- (NSData *)aes256_decrypt:(NSString *)key;
@end
// NSData+AES256.m
//#import "NSData+AES256.h"
@implementation NSData (AES256)
/** 加密 */
- (NSData*)aes256_encrypt:(NSString *)key
{
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
/** 解密 */
- (NSData*)aes256_decrypt:(NSString *)key
{
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [self bytes], dataLength, buffer, bufferSize, &numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}
@end
22.GCD异步
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//通知主线程刷新
dispatch_async(dispatch_get_main_queue(), ^{
//回调或者说是通知主线程刷新,
});
});
23.头部图片下拉放大
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat heightWidthRatio = VideoHeaderHeight/ScreenWidth;
CGRect frame = self.headerView.frame;
frame.origin.y = offsetY;
frame.origin.x = offsetY/heightWidthRatio/2;
frame.size.height = -offsetY+VideoHeaderHeight;
frame.size.width=(-offsetY+VideoHeaderHeight)/heightWidthRatio;
}
24.获取版本号,DisPlayName等
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
_nameLabel.text = [infoDict objectForKey:@"CFBundleDisplayName"];
_versionLabel.text = [NSString stringWithFormat:@"版本号: V%@",[infoDict objectForKey:@"CFBundleShortVersionString"]];
_rightsLabel.text = [NSString stringWithFormat:@"%@ Jucailife.cn京ICP备 15058272",[[NSDate date] year]];
**25.常用监听事件 **
**键盘**
//键盘出现时
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
//键盘收回时
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
**TextField**
//适用场景,打字时弹出suggestion
//TextField 编辑状态时(通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:textField];
//或者 addTarget
UIControlEventEditingDidBegin = 1 << 16,//1 << 17 代表:2的17次方
UIControlEventEditingChanged = 1 << 17,//1 << 18 代表:2的18次方
UIControlEventEditingDidEnd = 1 << 18,//1 << 19 代表:2的19次方
UIControlEventEditingDidEndOnExit = 1 << 19,
[field addTarget:self action:@selector(textFieldDidChanged) forControlEvents:UIControlEventEditingDidBegin | UIControlEventValueChanged | UIControlEventEditingDidEnd];
**26.监听ScrollView的滚动 **
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//偏移量
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY > 0) { //往上滑
}else {//往下滑
}
//加速度
UIPanGestureRecognizer* pan = scrollView.panGestureRecognizer;
CGFloat velocity = [pan velocityInView:scrollView].y;
if (velocity<-5) { //上
}else if (velocity>5) { //下
}
}
27.字符串编码
有的时候咱们会碰见字符串里有一些特殊字符在转成URL的时候 会出现转换不了的情况,这个时候需要对字符串进行编码9.0以前使用stringByAddingPercentEscapesUsingEncoding
9.0之后使用stringByAddingPercentEncodingWithAllowedCharacters
NSString *resourcePath = @"http://www.baidu.com?tickets=[{\"num\":\"1\",\"priceId\":\"8a82824756\"}]";
NSString *encodePath ;
if (!IOS7_OR_LATER) {
encodePath = [resourcePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}else{
encodePath = [resourcePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
}
28.ScrollView的ContentOffSet
[图片上传失败...(image-3a5507-1517802558316)]
29.ImageView填充方式。
[图片上传失败...(image-2d5dce-1517802558316)]
30.绘制一条虚线。
/*
**lineFrame: 虚线的frame
**length: 虚线中短线的宽度
**spacing: 虚线中短线之间的间距
**color: 虚线中短线的颜色
*/
+(UIView *)creatDashedLineWithFrame:(CGRect)lineFrame lineLenght:(int)length lineSpacing:(int)spacing lineColor:(UIColor *)color{
UIView *dashLine = [[UIView alloc]initWithFrame:lineFrame];
dashLine.backgroundColor = [UIColor clearColor];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:dashLine.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashLine.frame)/2, CGRectGetHeight(dashLine.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
[shapeLayer setStrokeColor:color.CGColor];
[shapeLayer setLineWidth:CGRectGetHeight(dashLine.frame)];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length],[NSNumber numberWithInt:spacing],nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashLine.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
[dashLine.layer addSublayer:shapeLayer];
return dashLine;
}
31. 播放视频。
#import
// =================================================
#pragma mark - 播放视频
// =================================================
+(void)playVideoWithUrl:(NSString *)url andController:(UIViewController *)controller{
MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:url]];
playerVC.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
// playerVC.moviePlayer.repeatMode = MPMovieRepeatModeOne;
[controller presentMoviePlayerViewControllerAnimated:playerVC];
}
+(void)playVideoWithLocalPath:(NSString *)localDocumentName andController:(UIViewController *)controller{
NSString *path = [[NSBundle mainBundle] pathForResource:localDocumentName ofType:nil];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
playerVC.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
// playerVC.moviePlayer.repeatMode = MPMovieRepeatModeOne;
[controller presentMoviePlayerViewControllerAnimated:playerVC];
}
** 32. iPhone屏幕尺寸、分辨率及适配。**
看这个大神的帖子足够
** 33. 验证邮箱、电话、和QQ **
- (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 *)phone
{
NSString *MOBILE = @"^1[34578]\\\\d{9}$";
NSPredicate *regexTestMobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",MOBILE];
if ([regexTestMobile evaluateWithObject:phone]) {
return YES;
}else {
return NO;
}
}
//QQ号码验证
- (BOOL)validateQQ:(NSString *)qq{
NSString *QQ = @"[1-9][0-9]{4,}";
NSPredicate *regexTestQQ = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",QQ];
if ([regexTestQQ evaluateWithObject:qq]) {
return YES;
}else {
return NO;
}
}
** 34. UISegmentedControl(直接拷来用)**
-(UISegmentedControl *)segementControl{
if (_segementControl == nil) {
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"餐馆", @"菜单"]];
segmentedControl.frame = CGRectMake((ScreenWidth-150)/2, 10, 150, 30);
// 设置进入页面后的所处的位置
segmentedControl.selectedSegmentIndex = 0;
//选中的颜色
segmentedControl.tintColor = [UIColor redColor];
[segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
[self.segementWrapView addSubview:segmentedControl];
_segementControl = segmentedControl;
}
return _segementControl;
}
- (void)segmentedControlValueChanged:(UISegmentedControl *) segmentedControl {
if (0 == segmentedControl.selectedSegmentIndex) {
}
}
** 35. iOS一键加群**
- (BOOL)joinGroup:(NSString *)groupUin key:(NSString *)key{
NSString *urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard? src_type=internal&version=1&uin=%@&key=%@&card_type=group&source=external", @"240555441",@"60d319547ddffeacefe646f0d273e988a26dc70065bdedfd6a63c484e3c353c0"];
NSURL *url = [NSURL URLWithString:urlStr];
if([[UIApplication sharedApplication] canOpenURL:url]){
[[UIApplication sharedApplication] openURL:url];
return YES;
}else return NO;
}
** 36.CLLocation的一些黑魔法**
(1).pausesLocationUpdatesAutomatically
locationManager.pausesLocationUpdatesAutomatically = NO;
贴上一段官网对这个属性的描述:
Allowing the location manager to pause updates can improve battery life on the target device without sacrificing location data. When this property is set to YES, the location manager pauses updates (and powers down the appropriate hardware) at times when the location data is unlikely to change. For example, if the user stops for food while using a navigation app, the location manager might pause updates for a period of time. You can help the determination of when to pause location updates by assigning a value to the activityTypeproperty.
大致的意思就是如果这个属性设置成YES(默认的也是YES),那么系统会检测如果设备有一段时间没有移动,就会自动停掉位置更新服务。这里需要注意的是,一旦定位服务停止了,只有当用户再次开启App的时候定位服务才会重新启动。
这里的一段时间是系统自动判定的,可以通过设置activityTypeproperty这个属性来决定这个时间的长短。
API的意思是,类似导航类的App,系统检验的时间会稍长一点,想运动类的App,就会比导航类的短一点。但是具体时间还是由系统来决定。
(2).headingFilter
locationManager.headingFilter = 45;//设置只有当设备方向的改变值超过该属性值时才激发delegate的方法。
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
MKAnnotationView *anv = [_mapView viewForAnnotation:_mapView.userLocation];
anv.transform = CGAffineTransformMakeRotation(newHeading.magneticHeading/360.0*2*M_PI);
}
(3).deferredUpdates
默认地,定位服务的代理会每秒钟都更新一次位置,这样对电池的消耗量会特别地大。除了设置pausesLocationUpdatesAutomatically这个属性以外,iOS还提供了DeferredUpdates的机制。
官方API文档:
- (void)allowDeferredLocationUpdatesUntilTraveled:(CLLocationDistance)distance timeout:(NSTimeInterval)timeout
distance:
The distance (in meters) from the current location that must be travelled before event delivery resumes. To specify an unlimited distance, pass the CLLocationDistanceMaxconstant.
timeout:
The amount of time (in seconds) from the current time that must pass before event delivery resumes. To specify an unlimited amount of time, pass the CLTimeIntervalMax constant.
就是你可以设置让系统每隔多远或者每隔多长时间更新一次位置。注意是“或”的关系,满足一个就会更新。
使用这个方法有很多要注意的地方:
desiredAccuracy必须设置成kCLLocationAccuracyBest
distanceFilter必须设置成kCLErrorDeferredDistanceFiltered
必须能够使用GPS进行定位(而不仅仅是移动数据或者Wi-Fi)
非常重要的一点,DeferredUpdates只会出现在设备进入低耗电量的状态,App运行在前台或者设备连接在Xcode上正在调试是不会触发的。(所以不可能在Debug的时候打印Log来检验,要调试的话,需要写一些Log存在本地的数据库)
** 37.真机中.Plist文件的读写**
.Plist文件的读写默认真机不管用,因为在真机环境下,App在Xcode中的Resources文件夹都是不可写的.所以我们要在App第一次运行时将需要修改且长久保存的数据放到Document目录下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self initDataFile];
return YES;
}
//在Document目录中初始化地图数据文件,因为该目录下文件可写且可以持久保存
-(void)initDataFile
{
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//取得目标文件路径
NSString *path = [docPath stringByAppendingPathComponent:@"titleList.plist"];
NSFileManager *fm = [NSFileManager defaultManager];
//如果目标文件不存在说明是App第一次运行,需要将相关可修改数据文件拷贝至目标路径.
if (![fm fileExistsAtPath:path]) {
NSError *error = nil;
//取得源文件路径
NSString *paths = [[NSBundle mainBundle] pathForResource:@"titleList" ofType:@"plist"];
if (![fm copyItemAtPath:paths toPath:path error:&error]) {
}
}
}
//.Plist文件的读写
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strDocBase = ([arrPaths count] > 0) ? [arrPaths objectAtIndex:0] : nil;
_path = [strDocBase stringByAppendingPathComponent:@"titleList.plist"];
//读取数据
NSArray *data = [NSArray arrayWithContentsOfFile:_path];
//写入数据
[_datas writeToFile:_path atomically:YES];
** 38.UITableView的Group样式下顶部空白处理**
//分组列表头部空白处理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;
** 39.获取某个view所在的控制器**
- (UIViewController *)viewController{
UIViewController *viewController = nil;
UIResponder *next = self.nextResponder;
while (next){
if ([next isKindOfClass:[UIViewController class]]){
viewController = (UIViewController *)next;
break;
}
next = next.nextResponder;
}
return viewController;
}
** 40.两种方法删除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];
}
** 41.获取图片某一点的颜色**
- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image
{
UIColor* color = nil;
CGImageRef inImage = image.CGImage;
CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
if (cgctx == NULL) {
return nil; /* error */
}
size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}};
CGContextDrawImage(cgctx, rect, inImage);
unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL) {
int offset = 4*((w*round(point.y))+round(point.x));
int alpha = data[offset];
int red = data[offset+1];
int green = data[offset+2];
int blue = data[offset+3];
color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:
(blue/255.0f) alpha:(alpha/255.0f)];
}
CGContextRelease(cgctx);
if (data) {
free(data);
}
return color;
}
** 42.禁止锁屏
**
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
** 43.模态推出透明界面**
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];
** 44.iOS 获取汉字的拼音**
+ (NSString *)transform:(NSString *)chinese{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近结果
return pinyin;
}
** 45.判断对象是否遵循了某协议**
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}
** 46.判断view是不是指定视图的子视图
**
BOOL isView = [textView isDescendantOfView:self.view];
** 47.取消UICollectionView的隐式动画**
UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。
下面几种方法都可以帮你去除这些动画
//方法一
[UIView performWithoutAnimation:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];
//方法二
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:nil];
}];
//方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
[UIView setAnimationsEnabled:YES];
}];