2014年2月6日 星期四

將NavigationBar從iOS6過渡到iOS7

首先需要判斷目前runtime是iOS6或是iOS7,使用下列macro

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

在iOS6裡面NavigationBar的顏色是用tintColor去設定

self.navigationController.navigationBar.tintColor = [UIColor whiteColor]

但是在iOS7裡面設定tintColor會把BackButton蓋掉,所以需要判斷version決定使用tintColor或是barTintColor。

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        self.navigationController.navigationBar.barTintColor = [UIColor greenColor];
}
else {
    self.navigationController.navigationBar.tintColor = [UIColor greenColor];
}

如果預設BackButton的顏色與目前tintColor不相配,需要改變顏色,但是又不想把全部的BarButtonItem樣式改掉時,可以用下面這樣的code。第一行會判斷UIBarButtonItem是否在UINavigationBar裡面,是才改變樣式。第二行是修改箭頭的顏色。

//set back button color
        [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
//set back button arrow color
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

沒有留言:

張貼留言