2014年2月7日 星期五

調整UIButton的Image大小

SetBackgroundImage

當給定一個固定大小的UIButton時,如果圖的大小跟UIButton不同,一種解法是

UIImage *image = [UIImage imageNamed:@"buttonImage"];
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(30.0f, 25.0f, 29.0f, 9.0f);
UIImage *resizeableImage = [image resizableImageWithCapInsets:edgeInsets];
[backButton setBackgroundImage:resizeableImage forState:UIControlStateNormal];

SetImage

如果背景圖已經用掉了,也就是UIButton現在已經有背景圖,但是前景還想再放一個跟按鈕大小不同的圖,這時可以利用UIButton裡的UIImageView。Stackoverflow上有教一個方法是

[button setContentMode:UIViewContentModeScaleAspectFit];

但是這個只能放大圖不能縮小圖。

另一種方法是透過設定imageEdgeInsets可以縮小Image

[button setImage:[UIImage imageNamed:@"buttonImage"] forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(10,20,10,20);

效果大概像這樣
original
Modified
圖片來自http://stackoverflow.com/questions/1957317/how-do-i-scale-a-uibuttons-imageview, Hitesh Savaliya的答案

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]];