在這裡總結一些iOS開發中的小技巧,能大大方便我們的開發,持續更新。

來源:互聯網
上載者:User

標籤:apple   alpha   amp   nbu   ide   panel   modal   system   對象   

UITableView的Group樣式下頂部空白處理//分組列表頭部空白處理UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];self.tableView.tableHeaderView = view;UITableView的plain樣式下,取消區頭停滯效果- (void)scrollViewDidScroll:(UIScrollView *)scrollView{    CGFloat sectionHeaderHeight = sectionHead.height;    if (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);    }}那個,其實,還是用Group樣式吧哈哈。擷取某個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;}兩種方法刪除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];}列印系統所有登入的字型名稱#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];Xcode調試不顯示記憶體佔用editSCheme  裡面有個選項叫叫做enable zoombie Objects  取消選中顯示隱藏檔案//顯示defaults write com.apple.finder AppleShowAllFiles -bool truekillall Finder //隱藏defaults write com.apple.finder AppleShowAllFiles -bool falsekillall 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) && [viewOrientationisEqualToString: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-12MMM: 月,顯示為英文月份簡寫,如 JanMMMM: 月,顯示為英文月份全稱,如 Janualydd: 日,2位元表示,如02d: 日,1-2位顯示,如 2EEE: 簡寫星期幾,如SunEEEE: 全寫星期幾,如Sundayaa: 上下午,AM/PMH: 時,24小時制,0-23K:時,12小時制,0-11m: 分,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監測IOS裝置是否設定了代理,需要CFNetwork.frameworkNSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURLURLWithString:@"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(@"設定了代理");}阿拉伯數字轉中文格式+(NSString *)translation:(NSString *)arebic{      NSString *str = arebic;    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];    NSArray *digits = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"];    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];     NSMutableArray *sums = [NSMutableArray array];    for (int i = 0; iBase64編碼與NSString對象或NSData對象的轉換// Create NSData objectNSData *nsdata = [@"iOS Developer Tips encoded in Base64"  dataUsingEncoding:NSUTF8StringEncoding]; // Get NSString from NSData object in Base64NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0]; // Print the Base64 encoded stringNSLog(@"Encoded: %@", base64Encoded); // Let‘s go the other way... // NSData from the Base64 encoded strNSData *nsdataFromBase64String = [[NSData alloc]  initWithBase64EncodedString:base64Encoded options:0]; // Decoded NSString from the NSDataNSString *base64Decoded = [[NSString alloc]  initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];NSLog(@"Decoded: %@", base64Decoded);取消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 ~/.lldbinitecho display @import UIKit >> ~/.lldbinitecho target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinitCocoaPods pod install/pod update更新慢的問題pod install --verbose --no-repo-updatepod 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);

  

在這裡總結一些iOS開發中的小技巧,能大大方便我們的開發,持續更新。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.