分享一些iOS開發實用的小技巧_IOS

來源:互聯網
上載者:User

1.設定navigationbar title顏色

 UIColor *whiteColor = [UIColor whiteColor];NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];[self.navigationController.navigationBar setTitleTextAttributes:dic];

2.擷取UIColor RGB

 UIColor *color = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];const CGFloat *components = CGColorGetComponents(color.CGColor);NSLog(@"Red: %f", components[0]);NSLog(@"Green: %f", components[1]);NSLog(@"Blue: %f", components[2]);NSLog(@"Alpha: %f", components[3]);

3.修改textField的placeholder的字型顏色、大小

 [self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

4.將color轉為UIImage

 - (UIImage *)createImageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage;}

5.載入啟動圖的時候隱藏statusbar

在info.plist中加入Status bar is initially hidden 設定為YES

6.擷取按鈕title的size

/** * 擷取按鈕title的size */- (CGFloat)getBtnTitleWidth:(UIButton*)btn { CGSize titleSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:btn.titleLabel.font}]; return titleSize;}

7.設定Status bar顏色

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];[view setBackgroundColor:COLOR_APP_MAIN];[viewController.navigationController.navigationBar addSubview:view];

8.json轉dictionary,dictionary轉json

+ (NSString*)dictionaryToJson:(NSDictionary *)dic { NSError *parseError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];}
+(NSDictionary *)jsonToDic:(NSString*)jsonStr {  NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];  NSError *err;  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData               options:NSJSONReadingMutableContainers                error:&err];  return dic;}

9.是否允許推送

+(BOOL)isAllowedNotification{ if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {  UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];  if(UIUserNotificationTypeNone != setting.types) {   return YES;  } } NSLog(@"不允許推送"); return NO;}

10.磁碟空間相關

+ (NSString *)memoryFormatter:(long long)diskSpace { NSString *formatted; double bytes = 1.0 * diskSpace; double megabytes = bytes / MB; double gigabytes = bytes / GB; if (gigabytes >= 1.0)  formatted = [NSString stringWithFormat:@"%.2f GB", gigabytes]; else if (megabytes >= 1.0)  formatted = [NSString stringWithFormat:@"%.2f MB", megabytes]; else  formatted = [NSString stringWithFormat:@"%.2f bytes", bytes]; NSLog(@"fotmatted=%@",formatted); return formatted;}+ (NSString *)totalDiskSpace { long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue]; return [self memoryFormatter:space];}+ (NSString *)freeDiskSpace { long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue]; return [self memoryFormatter:freeSpace];}

11.修改了leftBarButtonItem如何恢複系統側滑返回功能

 //設定代理self.interactivePopGestureRecognizer.delegate = self;#pragma mark - <UIGestureRecognizerDelegate>//實現代理方法:return YES :手勢有效, NO :手勢無效- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{ //當導航控制器的子控制器個數 大於1 手勢才有效 return self.childViewControllers.count > 1;}

或者用第三方 UINavigationController+FDFullscreenPopGesture

12.使用UIAppearance在某個狀態下設定顏色,字型等不好使

只需要在對應的位置用layoutIfNeeded重新整理一下就可以了

13.設定圓形圖片

/** 設定圓形圖片(放到分類中使用) */- (UIImage *)cutCircleImage { UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0); // 擷取上下文 CGContextRef ctr = UIGraphicsGetCurrentContext(); // 設定圓形 CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextAddEllipseInRect(ctr, rect); // 裁剪 CGContextClip(ctr); // 將圖片畫上去 [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image;}

14.如果在xib中有一個控制項, 已經明確設定尺寸了,輸出的frame也是對的, 但是顯示出來的效果不一樣(比如尺寸變大了), 如果是這種情況一般就是autoresizingMask自動調整屬性在搞鬼!

解決辦法如下:

//xib的awakeFromNib方法中設定UIViewAutoresizingNone進行清空 - (void)awakeFromNib { self.autoresizingMask = UIViewAutoresizingNone;}

15.通過圖片Data資料第一個位元組 來擷取圖片副檔名

- (NSString *)contentTypeForImageData:(NSData *)data { uint8_t c; [data getBytes:&c length:1]; switch (c) {  case 0xFF:   return @"jpeg";  case 0x89:   return @"png";    case 0x47:   return @"gif";    case 0x49:   case 0x4D:   return @"tiff";    case 0x52:    if ([data length] < 12) {    return nil;   }   NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];   if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {    return @"webp";   }   return nil; } return nil;}

16.用0補全的方法

NSInteger count = 5;//02代表:如果count不足2位 用0在最前面補全(2代表總輸出的個數)NSString *string = [NSString stringWithFormat:@"%02zd",count];//輸出結果是: 05NSLog(@"%@", string);

總結

以上就是這篇文章的全部內容,希望本文中的這些小技巧能給大家開發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.