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);
//將秒數(shù)轉化為日期格式
NSDate *confromTimesp = [NSDatedateWithTimeIntervalSince1970:1363948516];
NSLog(@"1363948516 = %@",confromTimesp);//2013-03-22 10:35:16 +0000
//將秒數(shù)轉化為特定格式的日期格式
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.真機測試時出現(xiàn)的問題
No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=armv7, VA
運行報錯
出現(xiàn)的原因: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里執(zhí)行。
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.電池狀態(tài)欄改變顏色
方法一:不用修改plist
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
默認的黑色(UIStatusBarStyleDefault)
白色(UIStatusBarStyleLightContent)
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
方法二:需要修改plist
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
/ 設置狀態(tài)欄字體顏色中國移動的顏色改為白色(需要設置plist文件里的View controller-based status bar appearance屬性為NO;)
[UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
//隱藏項目中得狀態(tài)欄
[[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\. 如果有數(shù)字,直接使用 viewController.tabBarItem.badgeValue = @"1";
2\. 沒有數(shù)字,自己往tabbar加subView。
需要注意的是坐標x,y一定要是整數(shù),否則會有模糊。
UIImageView *dotImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"personinfo_unread@2x.png"]];
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、狀態(tài)加入事件通知中心
[center addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
5、用NSUserDefault保存用戶數(shù)據
使用方法:
保存:
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.有三種方式可以引入靜態(tài)庫文件
第一種方式:直接將對應平臺的.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\. 設置靜態(tài)庫的鏈接路徑,在Xcode的Project -> Edit Active Target -> Build -> Search Path -> Library Search Paths中添加您的靜態(tài)庫目錄,比如"$(SRCROOT)/../libs/Release$(EFFECTIVE_PLATFORM_NAME)",$(SRCROOT)宏代表您的工程文件目錄,$(EFFECTIVE_PLATFORM_NAME)宏代表當前配置是OS還是simulator
注:靜態(tài)庫中采用ObjectC++實現(xiàn),因此需要您保證您工程中至少有一個.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 <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
@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.常用監(jiān)聽事件 **
**鍵盤**
//鍵盤出現(xiàn)時
[[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 編輯狀態(tài)時(通知)
[[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.監(jiān)聽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的時候 會出現(xiàn)轉換不了的情況,這個時候需要對字符串進行編碼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 <MediaPlayer/MediaPlayer.h>
// =================================================
#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),那么系統(tǒng)會檢測如果設備有一段時間沒有移動,就會自動停掉位置更新服務。這里需要注意的是,一旦定位服務停止了,只有當用戶再次開啟App的時候定位服務才會重新啟動。
這里的一段時間是系統(tǒng)自動判定的,可以通過設置activityTypeproperty這個屬性來決定這個時間的長短。
API的意思是,類似導航類的App,系統(tǒng)檢驗的時間會稍長一點,想運動類的App,就會比導航類的短一點。但是具體時間還是由系統(tǒng)來決定。
(2).headingFilter
locationManager.headingFilter = 45;//設置只有當設備方向的改變值超過該屬性值時才激發(fā)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.
就是你可以設置讓系統(tǒng)每隔多遠或者每隔多長時間更新一次位置。注意是“或”的關系,滿足一個就會更新。
使用這個方法有很多要注意的地方:
desiredAccuracy必須設置成kCLLocationAccuracyBest
distanceFilter必須設置成kCLErrorDeferredDistanceFiltered
必須能夠使用GPS進行定位(而不僅僅是移動數(shù)據或者Wi-Fi)
非常重要的一點,DeferredUpdates只會出現(xiàn)在設備進入低耗電量的狀態(tài),App運行在前臺或者設備連接在Xcode上正在調試是不會觸發(fā)的。(所以不可能在Debug的時候打印Log來檢驗,要調試的話,需要寫一些Log存在本地的數(shù)據庫)
** 37.真機中.Plist文件的讀寫**
.Plist文件的讀寫默認真機不管用,因為在真機環(huán)境下,App在Xcode中的Resources文件夾都是不可寫的.所以我們要在App第一次運行時將需要修改且長久保存的數(shù)據放到Document目錄下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self initDataFile];
return YES;
}
//在Document目錄中初始化地圖數(shù)據文件,因為該目錄下文件可寫且可以持久保存
-(void)initDataFile
{
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//取得目標文件路徑
NSString *path = [docPath stringByAppendingPathComponent:@"titleList.plist"];
NSFileManager *fm = [NSFileManager defaultManager];
//如果目標文件不存在說明是App第一次運行,需要將相關可修改數(shù)據文件拷貝至目標路徑.
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"];
//讀取數(shù)據
NSArray *data = [NSArray arrayWithContentsOfFile:_path];
//寫入數(shù)據
[_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.模態(tài)推出透明界面**
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.判斷對象是否遵循了某協(xié)議**
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];
}];