iOS5에서 UINavigationBar에 배경이미지와 타이틀 색깔 변경하기 (Change UINavigationBar background image and title color)
2011/11/09 23:38
배경 이미지에 사용할 이미지는 디바이스 가로 길이보다 길게 준비한다. 예제에 사용한 배경이미지를 잘 살펴보면 특정 패턴이 존재하고 있다. 파란색 배경부분을 유시힘 살펴보면 기존의 4:6과 같은 비율로 나타나 있지만 실제 배경화면으로 만들어진 것을 보면 그 비율이 틀리다. 이것은 UIImage의 또다른 속성으로 이미지를 가상으로 stretch 시켜서 그렇다. 쉽게 말해서 이미지를 특정 부분부터 잡아 늘려서 이미지를 다시 그린것과 같은 효과로 만든 것이다. 이 배경이미지는 실제로 프로젝트에 사용했던 배경 이미지이고 메뉴마다 왼쪽 UIBarButtonItem의 길이가 달라짐에 따라서 배경 이미지의 파란색 부분이 길어들고 줄어들면서 배경이미지를 변경 시켰었다.
iOS5에서는 특정 UIKit이 나타날때 적용시킬수 있는 메소드가 존재하는데 바로 appearance 메소드이다. [UIBarButtonItem appearance]라고 하면 UIBarButtonItem의 객체가 출현될때 불러져서 그 객체를 반환하는 메소드이다.
nib 파일이 로드될때 불러지는
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
메소드 안에서 appearance 메소드로 해당 객체에 설정을 할 수 있다.먼저 UINavigationBar가 나타날때 UIImage를 배경이미지로 설정한다고 해보자. initWithNibName:bundle: 메소드 안에서 다음과 같은 코드를 넣는다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
UIImage *backgroundImage = [UIImage imageNamed:@"hbn_top_bg_long.png"];
[[UINavigationBar appearance] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
}
return self;
}
그런데 이렇게해서 배경이미지를 넣으면 아래 그림과 같이 실망스런 결과가 나온다. 배경이미지 위치도 마음에 안들고, 타이틀 색깔도 배경 이미지 색깔과 너무 유사해서 눈에 들어오지도 않는다. (배경 이미지를 leftBarButtonItem 까지 늘리는 것을 설정하기 위해서 UIBarButtonItem을 하나 만들어서 self.navigationItem.leftBarButtonItem에 추가한 상태이다.)
우선 leftBarButton의 색상부터 변경해보자. 포토샵이나 RGB색상 체계를 사용하기 위해서 RGB 색상을 UIColor로 변환해주는 RGB메크로 메소드를 하나 만들었다.
다음은 앞에서 설정했듯 nib가 로드될때 적용시키 위해서 initWithNibName:bundle: 메소드 안에서 UIBarButtonItem의 appearance를 이용해서 버턴이 나타날때 적용되도록 한다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
UIImage *backgroundImage = [UIImage imageNamed:@"hbn_top_bg_long.png"];
[[UINavigationBar appearance] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTintColor:HBNRGB(3, 72, 176)];
}
return self;
}
다시 빌드와 런을 해보면 다음 그림과 같이 UIBarButtonItem의 색상이 변경된 것을 확인할 수 있다.
다음은 배경화면의 파란 부분을 어떻게하면 왼쪽으로 이동시킬수 있는지 보자. 이렇게 특정 이미지의 영역을 늘이거나 하는 기능은 iOS5부터 UIImage 클래스에 새롭게 추가된 resizableImageWithCapInsets: 메소드를 사용하면 할 수 있다. 이때 UIEdgeInsetsMake를 이용하는데 UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)로 저정한다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
UIImage *backgroundImage = [[UIImage imageNamed:@"hbn_top_bg_long.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 310)];
[[UINavigationBar appearance] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTintColor:HBNRGB(3, 72, 176)];
}
return self;
}
이제 타이틀 색깔을 변경해보자. 코코아 프로그램을 하고 iOS SDK에서 TextAttributes 속성이 있는지 한참을 찾았던 기억이 난다. iOS5 부터는 이 텍스트에 관한 속성을 Cocoa 개발처럼 사용할 수 있게 되었다. UITextAttributeTextColor로 색깔을 지정할 수 있고, UITextAttributeTextShadowColor로 그림자 색깔을 지정할 수 있고, UITextAttributeTextShadowOffset으로 그림자 영역도 설정할 수 있다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
UIImage *backgroundImage = [[UIImage imageNamed:@"hbn_top_bg_long.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 310)];
[[UINavigationBar appearance] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:HBNRGB(3, 72, 176), UITextAttributeTextColor, [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset, nil]];
[[UIBarButtonItem appearance] setTintColor:HBNRGB(3, 72, 176)];
}
return self;
}이 예제는 단순하게 배경 이미지를 다르게 변경하여 고정으로 위치 시켰지만 응용하여 보여질때마다 UIEdgeInsetsMake의 값을 변경하여 새롭게 배경 이미지를 늘리고 이동시키고 할수 있을 것이다.