本文對應github地址Tip002,如果由于github調整導致資源找不到,請訪問github
50.判斷字符串是否是整型
- (BOOL)isPureInt:(NSString *)string {
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return [scan scanInt:&val] && [scan isAtEnd];
}
51.字符串數字當位數不夠時補0
// *號當占位符
_minuteLabel.text = [NSString stringWithFormat:@"%0*d",wid, minute];
// 直接寫位數
_secondLabel.text = [NSString stringWithFormat:@"%02d",second];
52.weakSelf,strongSelf定義
__weak __typeof__ (self)weakSelf = self;
__strong __typeof__ (weakSelf)strongSelf = weakSelf;
宏定義(autoreleasepool方式需要添加@符號)
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
53.狀態欄高度和導航欄高度
狀態欄通常高度20(X系列44)但在通話中和有熱點連接時+20,所以最好別寫死
-
獲取狀態欄高度
[[UIApplication sharedApplication] statusBarFrame].size.height
-
狀態欄發生變化通知
UIApplicationWillChangeStatusBarFrameNotification UIApplicationDidChangeStatusBarFrameNotification
-
獲取導航欄高度(View中需要先獲取導航控制器)
self.navigationController.navigationBar.frame.size.height
54. 終端Vim編輯器顯示行號
按esc,輸入: 然后輸入set number回車
55.移除子視圖
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
56. 在線工具
57. button文字居左顯示
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
58.Mac系統顯示/隱藏文件
顯示:defaults write com.apple.finder AppleShowAllFiles -bool true
隱藏:defaults write com.apple.finder AppleShowAllFiles -bool false
59. 獲取keywindow
-
兩者區別請移步百度(比如彈出了Alert時用哪個)
#define DDYKeyWindow \ [[[UIApplication sharedApplication] delegate] window] ? \ [[[UIApplication sharedApplication] delegate] window] : \ [[UIApplication sharedApplication] keyWindow]
60. 網絡請求序列化
- (NSString *)changeToString:(id)sender {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sender options:NSJSONWritingPrettyPrinted error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
// [self changeToString:array];
61.判斷空值
-
判斷空值別直接 if (str) ,如果字符串為空描述時可能出現問題
- (BOOL)isBlankString:(NSString *)string { if (string == nil || string == NULL || [string isKindOfClass:[NSNull class]]) { return YES; } if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) { return YES; } return NO; }
62.判斷只有數字、小數點和減號
-
引申只包含給定字符串中字符
#define NUMBERS @"0123456789.-" #pragma mark -是否只包含數字,小數點,負號 - (BOOL)isOnlyhasNumberAndpointWithString:(NSString *)string { NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet]; NSString *filter=[[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filter]; }
63.判斷系統版本
-
以前
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) { } else { }
-
現在
if (@available(iOS 10.0, *)) { // [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil]; } else { // [[UIApplication sharedApplication] openURL:url]; }
64. NSNotificationCenter
-
需要接收通知的地方注冊觀察者
//獲取通知中心單例對象 NSNotificationCenter * center = [NSNotificationCenter defaultCenter]; //添加當前類對象為一個觀察者,name和object設置為nil,表示接收一切通知 [center addObserver:self selector:@selector(notice:) name:@"123" object:nil];
-
發送通知消息
//創建一個消息對象 NSNotification * notice = [NSNotification notificationWithName:@"123" object:nil userInfo:@{@"1":@"123"}]; //發送消息 [[NSNotificationCenter defaultCenter]postNotification:notice];
-
回調的函數中取到userInfo內容
- (void)notice:(id)sender{ NSLog(@"%@",sender); }
65. 監聽耳機的插拔
// 監聽耳機的插拔
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
// 相應的事件
- (void)routeChange:(NSNotification *)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger roteChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (roteChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
//插入耳機
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
//拔出耳機
NSLog(@"拔出耳機");
[self pausePlay];
break;
}
}
66. 點擊耳機中鍵的事件
-
首先要在程序入口處讓app接收遠程控制事件
//讓app支持接收遠程控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder];
-
然后在遠程事件通知中進行相應的操作(這個通知還會接收系統上拉菜單中的控制中心的播放和暫停按鈕)
//app接受遠程控制(控制中心 耳機等) - (void)remoteControlReceivedWithEvent:(UIEvent *)event { if (event.type == UIEventTypeRemoteControl) { switch (event.subtype) { case 100: //控制中心的播放按鈕 [[PlayingManager defaultManager] musicPlay]; break; case 101: //控制中心的暫停按鈕 [[PlayingManager defaultManager] pausePlay]; break; case 103:{ //耳機的單擊事件 根據音樂的播放狀態選擇暫停或播放 if ([[PlayingManager defaultManager] getStateOfPlayer]) { [[PlayingManager defaultManager] pausePlay]; } else { [[PlayingManager defaultManager] musicPlay]; } } break; case 104: //耳機的雙擊中鍵事件 [[PlayingManager defaultManager] nextMusic]; break; case 105: //耳機的中鍵盤點擊三下觸發的時間 [[PlayingManager defaultManager] beforeMusic]; break; default: break; } } }
67. 檢測程序是在真機上還是在模擬器上
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR 1
#elif TARGET_OS_IPHONE
#define SIMULATOR 0
#endif
68. 刪除MacOS自帶輸入法
69. 稍后執行與取消
-
情景:連麥邀請A,A不回應導致無法邀請其他人,此時就要設定超時。但A回應了就要取消超時
// selector 和 object 兩次調用要是一致的 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(inviteTimeOut:) object:userID]; [self performSelector:@selector(inviteTimeOut:) withObject:userID afterDelay:100];
70. 防止點擊cell后仍為灰色
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
71. 沙盒
/* 默認情況下,每個沙盒含有3個文件夾:Documents, Library 和 tmp
Documents:蘋果建議將程序中建立的或在程序中瀏覽到的文件數據保存在該目錄下,iTunes備份和恢復的時候會包括此目錄
Library:存儲程序的默認設置或其它狀態信息;
Library/Caches:存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應用退出刪除
tmp:提供一個即時創建臨時文件的地方。
iTunes在與iPhone同步時,備份所有的Documents和Library文件。
iPhone在重啟時,會丟棄所有的tmp文件。
*/
// 獲取Cache目錄:
NSArray*paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"%@", path);
// 獲取documents目錄:
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);
// 獲取Libarary目錄:
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"%@", path);
// 獲取tmp目錄:
NSString*tmpDir = NSTemporaryDirectory();
NSLog(@"%@", tmpDir);
// NSFileManager創建目錄、文件
// 創建文件:
NSString*rootPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
NSString*plistPath = [rootPathstringByAppendingPathComponent:@"hhk.plist"];
NSFileManager *fileManager = [NSFileManagerdefaultManager];
if(![fileManager fileExistsAtPath:plistPath]) {
[fileManagercreateFileAtPath:plistPathcontents:nilattributes:[NSDictionarydictionary]]; //創建一個dictionary文件
}
// 寫入文件:
NSMutableDictionary *dictionary= [NSMutableDictionary dictionary];
[mutableDictionarywriteToFile:plistPath atomically:YES]
// 讀取文件:
NSMutableDictionary *dictionary= [NSDictionarydictionaryWithContentsOfFile:plistPath];
// 創建目錄:
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory =[pathsobjectAtIndex:0];
NSLog(@"documentsDirectory%@",documentsDirectory);
NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSString*testDirectory =[documentsDirectorystringByAppendingPathComponent:@"test"]; // 創建目錄
[fileManagercreateDirectoryAtPath:testDirectorywithIntermediateDirectories:YESattributes:nil error:nil];
// http://www.cnblogs.com/uncle4/p/5547514.html
72. 隱藏導航欄分割線
@property (nonatomic, strong) UIView *navLine; //導航分割線
UIView *backgroundView = [self.navigationController.navigationBar subviews].firstObject;
// _navLine = backgroundView.subviews.firstObject;
for (UIView *view in backgroundView.subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.ddy_h == 0.5)
{
_navLine = (UIImageView *)view;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
_navLine.hidden = YES;
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
{
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
_navLine.hidden = NO;
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
{
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
}
73. Cell不重用
用同Cell不同ID
-
UICollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = [NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row]; [_collectionView registerClass:[NAHomeSkillListAllCell class] forCellWithReuseIdentifier:identifier]; NAHomeSkillListAllCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; return cell; }
-
tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } return cell; }
74. 關閉側滑返回
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
{
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(doNothing:)];
[self.view addGestureRecognizer:pan];
-(void)doNothing:(UISwipeGestureRecognizer *)recognizer {
}
75. 帶超鏈接的文字
<TTTAttributedLabelDelegate>
@property (nonatomic, strong) TTTAttributedLabel *linkLabel;
- (TTTAttributedLabel *)linkLabel
{
if (!_linkLabel) {
_linkLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(margin, 0, LC_DEVICE_WIDTH-2*margin, 60)];
_linkLabel.linkAttributes = @{NSForegroundColorAttributeName:NAYX_APP_COLOR};
_linkLabel.delegate = self;
_linkLabel.numberOfLines = 0;
[self.contentView addSubview:_linkLabel];
}
return _linkLabel;
}
- (void)addTipView
{
NSMutableAttributedString *tipStr = [[NSMutableAttributedString alloc] initWithString:_title];
NSRange linkRange = {25, _title.length-25};
NSRange baseRange = {0, tipStr.length};
[tipStr addAttribute:NSForegroundColorAttributeName value:NAYX_Mid_Black range:baseRange];
[tipStr addAttribute:NSFontAttributeName value:NA_FONT(14) range:baseRange];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 6;
[tipStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:baseRange];
self.linkLabel.text = tipStr;
[self.linkLabel addLinkToURL:[NSURL URLWithString:@"openNewPage"] withRange:linkRange];
}
_title = @"該資質需要進行人工審核,請聯系考官后再返回填寫資料【官方考核(線上游戲)】"
76. 判斷是否耳機狀態
- (BOOL)isHeadphone
{
UInt32 propertySize = sizeof(CFStringRef);
NSString * state = nil;
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute ,&propertySize,&state);
if ([(NSString *)state rangeOfString:@"Headphone"].length || [(NSString *)state rangeOfString:@"HeadsetInOut"].length)
return YES;
else
return NO;
}
77. 改變headerfooter顏色
#pragma mark 代理方法改變headerfooter顏色
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([view isMemberOfClass:[UITableViewHeaderFooterView class]])
{
((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = [UIColor clearColor];
}
}
78. 視圖圓角和陰影共存
UIView *v=[[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
v.backgroundColor=[UIColor yellowColor];
//v.layer.masksToBounds=YES;這行去掉,否則會裁剪而使陰影消失
v.layer.cornerRadius=10;
v.layer.shadowColor=[UIColor redColor].CGColor;
v.layer.shadowOffset=CGSizeMake(10, 10); // 右下
v.layer.shadowOpacity=0.5;
v.layer.shadowRadius=5;
[self.view addSubview:v];
79.多級模態彈出視圖dismiss
UIViewController *rootVC = self.presentingViewController;
while (rootVC.presentingViewController) {
rootVC = rootVC.presentingViewController;
}
[rootVC dismissViewControllerAnimated:YES completion:nil];
80.UITableViewStylePlain下防止HeaderFooterView懸停(懸浮)
/**
#pragma mark - 防止plain模式懸浮
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat sectionHeaderHeight = 50;
if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0,0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//headerView
if (scrollView == _tableView) {
//去掉UItableview的section的headerview黏性
CGFloat sectionHeaderHeight = _headerView.ddy_h;
if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
//footerView
if (scrollView == _tableView) {
//去掉UItableview的section的footerview黏性
CGFloat sectionFooterHeight = 55;
if (scrollView.contentOffset.y<=sectionFooterHeight && scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(0, 0, -sectionFooterHeight, 0);
} else if (scrollView.contentOffset.y>=sectionFooterHeight) {
scrollView.contentInset = UIEdgeInsetsMake(0, 0, -sectionFooterHeight, 0);
}
}
}
/*
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat sectionHeaderHeight = _headerView.ddy_h;
CGFloat sectionFooterHeight = 55;
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY >= 0 && offsetY <= sectionHeaderHeight)
{
scrollView.contentInset = UIEdgeInsetsMake(-offsetY, 0, -sectionFooterHeight, 0);
}else if (offsetY >= sectionHeaderHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight)
{
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, -sectionFooterHeight, 0);
}else if (offsetY >= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height)
{
scrollView.contentInset = UIEdgeInsetsMake(-offsetY, 0, -(scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight), 0);
}
}
*/
81. 根據時間戳獲取時間
很多情況需要根據時間戳計算是幾分鐘前,幾小時前或者幾天前
-
#pragma mark 返回相對時間 2小時前 - (NSString *)updateTimeForRow:(NSString *)lastTimeStr { // 獲取當前時時間戳 1466386762.345715 十位整數 6位小數 NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]; // 最后登錄時間戳(后臺返回的時間) NSTimeInterval createTime = [lastTimeStr longLongValue]/((lastTimeStr.length == 13)?1000:1); // 時間差 NSTimeInterval time = currentTime - createTime; NSInteger sec = time/60; if (sec<60) { return [NSString stringWithFormat:@"%ld分鐘前",sec]; } // 秒轉小時 NSInteger hours = time/3600; if (hours<24) { return [NSString stringWithFormat:@"%ld小時前",hours]; } //秒轉天數 NSInteger days = time/3600/24; if (days < 30) { return [NSString stringWithFormat:@"%ld天前",days]; } //秒轉月 NSInteger months = time/3600/24/30; if (months < 12) { return [NSString stringWithFormat:@"%ld月前",months]; } //秒轉年 NSInteger years = time/3600/24/30/12; return [NSString stringWithFormat:@"%ld年前",years]; }
-
返回年月日時分秒
#pragma mark 返回年月日時分秒 - (NSString *)timeToString:(NSString *)str { if ([self isBlankString:str]) { return @""; } NSTimeInterval time = [str doubleValue];//+28800;//因為時差問題要加8小時 == 28800 sec NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time]; NSLog(@"date:%@",[detaildate description]); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM月dd日 HH:mm"]; NSString *currentDateStr = [dateFormatter stringFromDate: detaildate]; return currentDateStr; }
82. UISwitch改變大小
// 不能改變frame,采用縮放方式
switchBtn.transform = CGAffineTransformMakeScale(0.75, 0.75);
83. 時間
-
一般獲取
+ (NSString*)getCurrentTime { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //hh:12小時制 HH:24小時制 NSDate *dateNow = [NSDate date]; NSString *currentTimeString = [formatter stringFromDate:dateNow]; return currentTimeString; }
-
非國行可能出問題加 timeZone
/** * FDateFormatterStyle * kCFDateFormatterNoStyle 無輸出 * kCFDateFormatterShortStyle 10/29/12, 2:27 PM * kCFDateFormatterMediumStyle 10,29,2012, 2:39:56 PM * kCFDateFormatterLongStyle 10,29,2012, 2:39:56 PM GMT+08:00 * kCFDateFormatterFullStyle 星期日,10,29,2012, 2:39:56 PM China Standard Time * * * G: 公元時代,例如AD公元 * yy: 年的后2位 * yyyy: 完整年 * MM: 月,顯示為1-12 * MMM: 月,顯示為英文月份簡寫,如 Jan * MMMM: 月,顯示為英文月份全稱,如 Janualy * dd: 日,2位數表示,如02 * d: 日,1-2位顯示,如 2 * e: 1~7 (一周的第幾天, 帶0) * EEE: 簡寫星期幾,如Sun * EEEE: 全寫星期幾,如Sunday * aa: 上下午,AM/PM * H: 時,24小時制,0-23 * K:時,12小時制,0-11 * m: 分,1-2位 * mm: 分,2位 * s: 秒,1-2位 * ss: 秒,2位 * S: 毫秒 * Q/QQ: 1~4 (0 padded Quarter) 第幾季度 * QQQ: Q1/Q2/Q3/Q4 季度簡寫 * QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter 季度全拼 * zzz表示時區 * timeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"] * [NSTimeZone timeZoneForSecondsFromGMT:0*3600] */
84. NSString 和 NSURL轉化
NSURL *URL = [NSURL URLWithString:str]; //string>url
NSString *str1 = [URL absoluteString]; //url>string
85. safari保存的webAchirve轉html
終端 textutil -convert html (webarchive文件拖入)
85. git運用
86. UIButton改變imageView.contentMode
只控制setImage:forState:中圖片, 不能更改setBackGroundImage方式圖片
87.AVAudioPlayer播放聲音小的解決方案
NSError *categoryError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&categoryError];
[audioSession setActive:YES error:&categoryError];
NSError *audioError = nil;
BOOL success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&audioError];
if(!success)
{
NSLog(@"error doing outputaudioportoverride - %@", [audioError localizedDescription]);
}
88. 按鈕聲音播放動畫
- (void)playVoice:(UIButton *)button
{
if (![self isBlankString:_skillAptitudeModel.skill_audio])
{
[[NAChatVoicePlayer sharedInstance] setPlayPath:_skillAptitudeModel.skill_audio];
[NAChatVoicePlayer sharedInstance].audioCategory = AVAudioSessionCategoryPlayback;
NSError *categoryError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&categoryError];
[audioSession setActive:YES error:&categoryError];
NSError *audioError = nil;
BOOL success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&audioError];
if(!success)
{
NSLog(@"error doing outputaudioportoverride - %@", [audioError localizedDescription]);
}
[button setAdjustsImageWhenHighlighted:NO];
if ([_soundBtn.imageView isAnimating])
{
[_soundBtn.imageView stopAnimating];
}
UIImageView *imageView = button.imageView;
//設置動畫幀
imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"skill_voice1"],
[UIImage imageNamed:@"skill_voice2"],
[UIImage imageNamed:@"skill_voice3"],
nil];
// 設置動畫總時間
imageView.animationDuration = 0.6;
//設置重復次數,0表示無限
// imageView.animationRepeatCount = 5;
//開始動畫
if (! imageView.isAnimating)
{
[imageView startAnimating];
}
[self performSelector:@selector(stopButtonAnimation) withObject:nil afterDelay:[_skillAptitudeModel.audio_second integerValue]];
}
}
- (void)stopButtonAnimation
{
if ([_soundBtn.imageView isAnimating])
{
[_soundBtn.imageView stopAnimating];
}
}
89. 富文本計算高度
#pragma mark 文字高度
- (CGFloat)textH:(NSString *)text lineSpace:(CGFloat)lineSpace width:(CGFloat)width font:(UIFont *)font
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineSpacing = lineSpace;
NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:font};
CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
return size.height;
}
90.監聽網絡狀態
-
原生Reachability
方法一 :command + shift + 0打開 Documentation And API reference 搜索 Reachability
方法二:到網頁下載 -
獲取當前網絡狀態
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"]; NetworkStatus netStatus = [reachability currentReachabilityStatus]; switch (netStatus) { case NotReachable: break; case ReachableViaWiFi: networkStatus = break; case ReachableViaWWAN: break; default: break; }
-
監聽網絡狀態
- (void) addNotifacation { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; [self.hostReachability startNotifier]; } - (void) reachabilityChanged:(NSNotification *)note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass:[Reachability class]]); NetworkStatus netStatus = [reachability currentReachabilityStatus]; }
-
AFN 的二次封裝監聽
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { //結合MBProgressHUD進行顯示: case -1: //AFNetworkReachabilityStatusUnknown { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"未知網絡"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; case 0: //AFNetworkReachabilityStatusNotReachable { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"無法連接"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; case 1: //AFNetworkReachabilityStatusReachableViaWWAN { //這里是本文的核心點:采用遍歷查找狀態欄的顯示網絡狀態的子視圖,通過判斷該子視圖的類型來更詳細的判斷網絡類型 NSArray *subviewArray = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews]; int type = 0; for (id subview in subviewArray) { if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) { type = [[subview valueForKeyPath:@"dataNetworkType"] intValue]; } switch (type) { case 1: { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"當前為2G網絡"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; case 2: { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"當前為3G網絡"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; case 3: { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"當前為4G網絡"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; default: break; } } } break; case 2: //AFNetworkReachabilityStatusReachableViaWiFi { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"當前為WIFI"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; default: { //提示框: MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES]; textOnlyHUD.mode = MBProgressHUDModeText; textOnlyHUD.labelText = @"無網絡連接"; [textOnlyHUD hide:YES afterDelay:1.f]; } break; } }]; //開始監測 [[AFNetworkReachabilityManager sharedManager] startMonitoring];
-
獲取狀態欄信息方式
- (BOOL)checkNoNetwork{ BOOL flag = NO; UIApplication *app = [UIApplication sharedApplication]; NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews]; int netType = 0; //獲取到網絡返回碼 for (id child in children) { if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) { //獲取到狀態欄,飛行模式和關閉移動網絡都拿不到dataNetworkType;1 - 2G; 2 - 3G; 3 - 4G; 5 - WIFI netType = [[child valueForKeyPath:@"dataNetworkType"] intValue]; switch (netType) { case 0: flag = NO; //無網模式 break; default: flag = YES; break; } } } return flag; }
很遺憾的是在局域網時可能誤判,詳見Reachability檢測網絡狀態
91. iOS5后真機上條件亮度接口
[[UIScreen mainScreen] setBrightness: mSlider.value];
92.簡易更改push動畫
CATransition* transition = [CATransition animation];
transition.duration = 0.2;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[[NA_APPDELEGATE currentController].navigationController.view.layer addAnimation:transition
forKey:nil];
// 之后push
[self.navigationController pushViewController:vc animation:NO];
93. 跳轉到AppStore評分
-(void)goToAppStore
{
NSString *str = [NSString stringWithFormat:
@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d",547203890];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
94.判斷scrollView滾動方向
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint vel = [scrollView.panGestureRecognizer velocityInView:scrollView];
GTLog(@"%f",vel.y);
if (vel.y > 0) {
// 下拉
} else {
// 上拉
}
}
95. 獲取控件在屏幕上的相對位置
UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
if (!keyWindow) keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect=[bView convertRect: bView.bounds toView:keyWindow];
96. 關閉Mac SIP
97. 控件抖動
-(void)BeginWobble {
srand([[NSDate date] timeIntervalSince1970]);
float rand=(float)random();
CFTimeInterval t=rand*0.0000000001;
[UIView animateWithDuration:0.1 delay:t options:0 animations:^{
要抖動的視圖.transform=CGAffineTransformMakeRotation(-0.05);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction animations:^
{
要抖動的視圖.transform=CGAffineTransformMakeRotation(0.05);
} completion:^(BOOL finished) {}];
}];
}
-(void)EndWobble {
[UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState animations:^{
要抖動的視圖.transform=CGAffineTransformIdentity;
} completion:^(BOOL finished) {}];
}
98. 小數化整總結
99. 窗口中有多個Responder,如何快速釋放鍵盤
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];