您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone 開發實用技巧彙編:狀態列、動畫、音訊與常見瑣事

編輯:iOS 開發綜合

狀態列與螢幕方向

隱藏狀態列有兩種層次的做法。程式碼方式只是讓它「看不見」,佔用的 20pt 空間仍然存在:

 [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

若要連版面一起重排,則該改 Info.plist,新增一個 UIStatusBarHidden 鍵並把型別設為 Boolean,重新編譯後才會生效。切換方向同理:

 [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];

把專案名稱當成標題

 self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];

交互與按鈕狀態的三個易混屬性

  • userInteractionEnabled = NO:整個視圖不再接收任何觸摸事件
  • enabled = NO:按鈕變灰、失去回應,但外觀仍顯示
  • hidden = YES:直接不顯示

三者效果完全不同,選錯就會出現「按鈕明明在畫面上卻點不動」的困惑。

型別轉換

 int value = [string integerValue];               // 字串轉整數
NSString *s = [NSString stringWithFormat:@"%d", value];  // 整數轉字串

刷新列表與遍歷子視圖

 [self.tableView reloadData];
 for (UIView *oneView in cell.contentView.subviews) {
    if ([oneView isMemberOfClass:[UITextField class]]) {
        textField = (UITextField *)oneView;
    }
}

頁面翻轉動畫

 [UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:kTransitionDuration];
[UIView setAnimationTransition:([self.mainView superview] ?
    UIViewAnimationTransitionCurlUp : UIViewAnimationTransitionCurlDown)
    forView:self.containerView cache:YES];

if ([self.flipToView superview]) {
    [self.flipToView removeFromSuperview];
    [self.containerView addSubview:self.mainView];
} else {
    [self.mainView removeFromSuperview];
    [self.containerView addSubview:self.flipToView];
}
[UIView commitAnimations];

這是一維的翻頁效果,若想自訂旋轉軸心,透過圖層的 anchorPoint 設定即可:

 imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

隱藏導覽列與開啟地圖

 [self.navigationController setNavigationBarHidden:YES animated:YES];
 NSString *mapUrl = [NSString stringWithFormat:@"https://maps.google.com/maps?q=%f,%f",
                    loc.latitude, loc.longitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mapUrl]];

日期格式化

 NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"hh:mm:ss"];
NSString *str = [format stringFromDate:[NSDate date]];

透過通知觸發方法

 [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(xxx:) name:UIApplicationWillTerminateNotification object:nil];

背景音樂與短音效

長時間的背景音樂用 AVAudioPlayer,記得把 numberOfLoops 設為 -1 才能無限循環:

 myBackMusic.numberOfLoops = -1;
[myBackMusic prepareToPlay];
[myBackMusic setVolume:1];
[myBackMusic play];

短音效(例如按鈕點擊聲)則用 AudioServices 這組 C API, overhead 更低:

 AudioServicesCreateSystemSoundID(theSoundURL, &sameViewSoundID);
AudioServicesPlaySystemSound(sameViewSoundID);

UILabel 自動換行

 label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;   // 0 代表不限行數

以上都是 iOS 早期(Objective-C、MRC 時代)的寫法,在現代專案中多已改為 Auto Layout、AVAudioSession 與 blocks 動畫,但底層概念與思路完全相通,理解它們有助於看懂老專案的程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved