在 iOS 開發過程中,許多看似不重要的小技巧,往往能大幅提升效率或解決實際問題。以下整理常見且實用的做法,適合日常開發時參考。
若使用 Grouped 樣式的 UITableView,頂部可能出現空白。可以透過設定一個極小高度的 tableHeaderView 來解決:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;
你可以沿著 responder chain 往上尋找:
- (UIViewController *)viewController {
UIResponder *next = self.nextResponder;
while (next) {
if ([next isKindOfClass:[UIViewController class]]) {
return (UIViewController *)next;
}
next = next.nextResponder;
}
return nil;
}
若要一次清除所有 NSUserDefaults 內容,可以移除目前 App 的 persistent domain:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
這個方法可以幫助你快速找到系統支援的字體名稱:
for (NSString *familyName in [UIFont familyNames]) {
NSLog(@"%@", familyName);
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
NSLog(@" - %@", fontName);
}
}
若你的 App 是影片播放器或需要長時間顯示的應用,可以關閉自動鎖定:
[UIApplication sharedApplication].idleTimerDisabled = YES;
若需要讓背景保持可見,可以設定適當的 modalPresentationStyle:
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:na animated:YES completion:nil];
若想保留完整字元序列,可以使用 enumerateSubstringsInRange:
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];
}];
你可以利用 CFStringTransform 將中文轉為拼音,再去掉音標:
NSMutableString *pinyin = [chinese mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
若要計算最大值、最小值、平均值與總和,可以使用 KVC:
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];
你可以透過 navigationController 的 viewControllers 數量來判斷:
if (self.navigationController.viewControllers.count > 1) {
// 可能是 push
} else {
// 可能是 present
}
GCD timer 適合需要精準週期性執行的場景。使用 dispatch_source 建立計時器後,記得在不需要時取消,避免資源浪費。
這些技巧看似零散,卻很常出現在實際專案中。把它們整理成自己的工具庫,能讓開發更順手,也能減少重複搜尋的時間。