日常開發中積累的一些小技巧,多數都不長,但重複使用的頻率很高。整理成清單方便隨時翻查。
1. 設定 navigationBar 標題顏色
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. 把純色轉成 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. 啟動圖顯示期間隱藏狀態列
在 Info.plist 中加入 Status bar is initially hidden 並設為 YES。

6. 取得按鈕標題文字的尺寸
- (CGSize)getBtnTitleSize:(UIButton *)btn {
return [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: btn.titleLabel.font}];
}
7. 自訂狀態列顏色
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)]; [view setBackgroundColor:COLOR_APP_MAIN]; [viewController.navigationController.navigationBar addSubview:view];
8. 字典與 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;
return [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
}
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];
}
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>
// 回傳 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 中控制項尺寸明明正確卻顯示異常
這種情況多半是 autoresizingMask 自動伸縮屬性在搗鬼,在 awakeFromNib 中清掉即可:
- (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 代表:不足 2 位時在前面補 0(2 為總輸出位數) NSString *string = [NSString stringWithFormat:@"%02zd", count]; // 輸出結果:05 NSLog(@"%@", string);
以上就是這批小技巧的整理,若有任何疑問歡迎留言討論。