//分組列表頭部空白處理 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)]; self.tableView.tableHeaderView = 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; }
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]; }
#pragma mark - 打印系統所有已注冊的字體名稱 void enumerateFonts() { for(NSString *familyName in [UIFont familyNames]) { NSLog(@"%@",familyName); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for(NSString *fontName in fontNames) { NSLog(@"\t|- %@",fontName); } } }
- (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; }
- (NSString *)reverseWordsInString:(NSString *)str { NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length]; for (NSInteger i = str.length - 1; i >= 0 ; i --) { unichar ch = [str characterAtIndex:i]; [newString appendFormat:@"%c", ch]; } return newString; }第二種:
- (NSString*)reverseWordsInString:(NSString*)str { NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length]; [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [reverString appendString:substring]; }]; return reverString; }
默認情況下,當設備一段時間沒有觸控動作時,iOS會鎖住屏幕。但有一些應用是不需要鎖屏的,比如視頻播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
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];
editSCheme 裡面有個選項叫叫做
enable zoombie Objects取消選中
顯示隱藏文件
顯示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder
隱藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder
iOS跳轉到App Store下載應用評分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
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;
}
手動更改iOS狀態欄的顏色
- (void)setStatusBarBackgroundColor:(UIColor *)color
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
{
statusBar.backgroundColor = color;
}
}
判斷當前ViewController是push還是present的方式顯示的
NSArray *viewcontrollers=self.navigationController.viewControllers;
if (viewcontrollers.count > 1)
{
if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
{
//push方式
[self.navigationController popViewControllerAnimated:YES];
}
}
else
{
//present方式
[self dismissViewControllerAnimated:YES completion:nil];
}
獲取實際使用的LaunchImage圖片
- (NSString *)getLaunchImageName
{
CGSize viewSize = self.window.bounds.size;
// 豎屏
NSString *viewOrientation = @"Portrait";
NSString *launchImageName = nil;
NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
for (NSDictionary* dict in imagesDict)
{
CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
{
launchImageName = dict[@"UILaunchImageName"];
}
}
return launchImageName;
}
iOS在當前屏幕獲取第一響應
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
判斷對象是否遵循了某協議
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}
判斷view是不是指定視圖的子視圖
BOOL isView = [textView isDescendantOfView:self.view];
NSArray 快速求總和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
修改UITextField中Placeholder的文字顏色
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
關於NSDateFormatter的格式
G: 公元時代,例如AD公元
yy: 年的後2位
yyyy: 完整年
MM: 月,顯示為1-12
MMM: 月,顯示為英文月份簡寫,如 Jan
MMMM: 月,顯示為英文月份全稱,如 Janualy
dd: 日,2位數表示,如02
d: 日,1-2位顯示,如 2
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: 毫秒
獲取一個類的所有子類
+ (NSArray *) allSubclasses
{
Class myClass = [self class];
NSMutableArray *mySubclasses = [NSMutableArray array];
unsigned int numOfClasses;
Class *classes = objc_copyClassList(&numOfClasses;);
for (unsigned int ci = 0; ci < numOfClasses; ci++)
{
Class superClass = classes[ci];
do{
superClass = class_getSuperclass(superClass);
} while (superClass && superClass != myClass);
if (superClass)
{
[mySubclasses addObject: classes[ci]];
}
}
free(classes);
return mySubclasses;
}
監測IOS設備是否設置了代理,需要CFNetwork.framework
NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);
NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);
if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
NSLog(@"沒代理");
}
else
{
NSLog(@"設置了代理");
}
取消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];
}];
讓Xcode的控制台支持LLDB類型的打印
打開終端輸入三條命令:
touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
CocoaPods pod install/pod update更新慢的問題
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加後面的參數,默認會升級CocoaPods的spec倉庫,加一個參數可以省略這一步,然後速度就會提升不少
UIImage 占用內存大小
UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
GCD timer定時器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執行
dispatch_source_set_event_handler(timer, ^{
//@"倒計時結束,關閉"
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
});
});
dispatch_resume(timer);
圖片上繪制文字 寫一個UIImage的category
- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
{
//畫布大小
CGSize size=CGSizeMake(self.size.width,self.size.height);
//創建一個基於位圖的上下文
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0
[self drawAtPoint:CGPointMake(0.0,0.0)];
//文字居中顯示在畫布上
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
//計算文字所占的size,文字居中顯示在畫布上
CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
CGFloat width = self.size.width;
CGFloat height = self.size.height;
CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
//繪制文字
[title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
//返回繪制的新圖形
UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
查找一個視圖的所有子視圖
- (NSMutableArray *)allSubViewsForView:(UIView *)view
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
for (UIView *subView in view.subviews)
{
[array addObject:subView];
if (subView.subviews.count > 0)
{
[array addObjectsFromArray:[self allSubViewsForView:subView]];
}
}
return array;
}