iOS2012. 9. 3. 13:28

For Gigster’s navigation concept it was necessary to implement a custom styled tab bar. Basically the screen is divided into three parts:

  • Navigation Bar
  • Tab Bar
  • Content

The navigation bar has a custom background image and a fixed title with custom font. The tab bar should be directly under the navigation bar and has complete custom styling.

Basic Setup

To start off I created a new Xcode project and added a UITabBarController with three static views. Although I have XIBs for each content view, I added everything else in code. Each view has a UINavigationController so it can easily contain its own navigation stack.

Navigation Bar

An easy technique to get a custom background in a UINavigationBar is to make a cateogory. Add this code (e.g. in YourAppDelegate.m):

@interface UINavigationBar (MyCustomNavBar)
@end
@implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect 
{
    UIImage *barImage = [UIImage imageNamed:@"nav_bg.png"];
    [barImage drawInRect:rect];    
}
@end

To get the fixed title with custom font I added a method that creates a UILabel:

- (UILabel *)_makeTitleLabel
{
    CGRect frame = CGRectMake(0032044);
    UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont fontWithName:@"Marker Felt" size:24];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.text = @"Custom Tab Bar";
    
    return label;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ...
    // add static title labels
    [tab1NavigationController.navigationBar addSubview:[self _makeTitleLabel]];
    [tab2NavigationController.navigationBar addSubview:[self _makeTitleLabel]];
    [tab3NavigationController.navigationBar addSubview:[self _makeTitleLabel]];
    ...
}

Tab Bar

A little bit of frame hackery was necessary to get the tab bar right beneath the navigation bar:

    // disable autosizing of tabbar and move it to correct position
    tabBarController.tabBar.autoresizingMask = 0;
    tabBarController.tabBar.frame = CGRectMake(04432065);
    
    
    // fix frame of tabbarcontroller's view
    CGRect frame = tabBarController.view.frame;
    frame.size.height += 29;
    frame.origin.y = 20;
    tabBarController.view.frame = frame;

To have a custom layout for the tab bar, it is necessary to subclass UITabBarController. We don’t need UIKit’s tab bar at all, so we just hide it and create our own custom tabs:

- (void)viewDidLoad
{
    // find the normal tab bar and hide it
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            view.hidden = YES;
            break;
        }
    }
    
    [self _setupCustomTabBar];
}

First I added a UIImageView containing a background image:

- (void)_setupCustomTabBar
{
    // background image
    self.bgImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabs_bg.png"]] autorelease];
    bgImageView.frame = CGRectMake(04432065);
    [self.view addSubview:bgImageView];

Next we want to display a tab image to indicate which tab is active:

    self.contentView = [[[UIView alloc] initWithFrame:CGRectMake(04464065)] autorelease];
    [self.view addSubview:self.contentView];
    
    // sliding tab image
    self.tabImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tab.png"]] autorelease];
    CGRect frame = self.tabImage.frame;
    frame.origin = CGPointMake(BUTTON_X_OFFSET, BUTTON_Y);
    self.tabImage.frame = frame;
    [self.contentView addSubview:self.tabImage];

Finally I added three buttons to trigger tab selection:

    // Make custom tab buttons and add them to the content view
    [self.contentView addSubview:[self _makeTabButtonWithTitle:@"Tab 1" atIndex:0]];
    [self.contentView addSubview:[self _makeTabButtonWithTitle:@"Tab 2" atIndex:1]];
    [self.contentView addSubview:[self _makeTabButtonWithTitle:@"Tab 3" atIndex:2]];
}

Button creation method:

- (UIButton *)_makeTabButtonWithTitle:(NSString *)title
                              atIndex:(NSInteger)index
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(BUTTON_X_OFFSET + index*BUTTON_WIDTH, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT);
    button.tag = index;
    button.titleLabel.font = [UIFont fontWithName:@"Marker Felt" size:18];
    button.titleLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.5];
    button.titleLabel.shadowOffset = CGSizeMake(0-1);
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:@selector(_buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

Note that the buttons’ action is _buttonClicked. There we need to set the currently selected tab index in the UITabBarController.

- (void)_buttonClicked:(id)sender
{
    self.selectedIndex = [sender tag];
    [self _updateTabImage];
}

We also want to update the tab image’s position after a tab was selected. This is what _updateTabImage is for:

- (void)_updateTabImage
{
    CGRect targetRect = CGRectMake(BUTTON_X_OFFSET + self.selectedIndex*BUTTON_WIDTH, BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT);
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [self.tabImage setFrame:targetRect];
    
    [UIView commitAnimations];
}

Now we have a fully functioning tab bar with custom layout. You can download the full Xcode project here:MyCustomTabBar_final.zip.

Gigster in the App Store: Jump

Posted by 다오나무
카테고리 없음2012. 9. 3. 11:13

iOS 5 Tutorial: Creating a Custom Tab Bar Controller

I'm currently revamping an iPhone app that I made for the New Student Orientation Program at Columbia University. The app has this beautiful custom tab bar that my friend designed and so I am re-implementing it for iOS 5.

I literally just spent the last three hours figuring out how to do this so hopefully I can save you all time.

Finished Product:




1. Create a New Tabbed Application.



2. Go to the MainStoryboard file and drag and drop three view controllers and connect them to the tab bar controller.


When You're Finished You Should Have Five Views Connected Like This:


Note: Go to the right sidebar and delete the title for each of the toolbar buttons as well. Like this:




3. Because this is a tutorial about creating a custom tab bar, it's not necessary to create custom view controllers so I'm just going to use the auto generated FirstViewController.m file to do all of the work.

Download These Images: here.

My friend made these and so you can just download them and add them to your project. All of the images are 64px x 49px since 320px width / 5 = 64 px, and 49 px high because we thought that looked good.

The dark blue is for when the view is selected and the light blue is for when the view is unselected.

Note: The images were hard to format in Blogger hence the mess.





4. Drag and drop the downloaded images into your project.

 5. Go to the FirstViewController.m file and add the following code below in the viewDidLoad method. The code essentially says that for each tab bar item at the index, when selected set the image to the dark blue image and when the tab bar item is unselected set it to the light blue image.

Data provided by Pastebin.com - Download Raw - See Original
  1. - (void)viewDidLoad
  2. {
  3.     UIImage *selectedImage0 = [UIImage imageNamed:@"HomeDB.png"];
  4.     UIImage *unselectedImage0 = [UIImage imageNamed:@"HomeLB.png"];
  5.    
  6.     UIImage *selectedImage1 = [UIImage imageNamed:@"ScheduleDB.png"];
  7.     UIImage *unselectedImage1 = [UIImage imageNamed:@"ScheduleLB.png"];
  8.    
  9.     UIImage *selectedImage2 = [UIImage imageNamed:@"BuildingsDB.png"];
  10.     UIImage *unselectedImage2 = [UIImage imageNamed:@"BuildingsLB.png"];
  11.    
  12.     UIImage *selectedImage3 = [UIImage imageNamed:@"InformationDB.png"];
  13.     UIImage *unselectedImage3 = [UIImage imageNamed:@"InformationLB.png"];
  14.    
  15.     UIImage *selectedImage4 = [UIImage imageNamed:@"MoreDB.png"];
  16.     UIImage *unselectedImage4 = [UIImage imageNamed:@"MoreLB.png"];
  17.    
  18.     UITabBar *tabBar = self.tabBarController.tabBar;
  19.     UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
  20.     UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
  21.     UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
  22.     UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
  23.     UITabBarItem *item4 = [tabBar.items objectAtIndex:4];
  24.    
  25.     [item0 setFinishedSelectedImage:selectedImage0 withFinishedUnselectedImage:unselectedImage0];
  26.     [item1 setFinishedSelectedImage:selectedImage1 withFinishedUnselectedImage:unselectedImage1];
  27.     [item2 setFinishedSelectedImage:selectedImage2 withFinishedUnselectedImage:unselectedImage2];
  28.     [item3 setFinishedSelectedImage:selectedImage3 withFinishedUnselectedImage:unselectedImage3];
  29.     [item4 setFinishedSelectedImage:selectedImage4 withFinishedUnselectedImage:unselectedImage4];
  30.     [super viewDidLoad];
  31.         // Do any additional setup after loading the view, typically from a nib.
  32. }
  33.  


 6. Build and run and you should be good to go.






Download Project Here: here.

Posted by 다오나무
iOS2012. 6. 20. 21:10

제목그대로 인데요

아이폰에서 탭바를 사용시에

탭을 4개 넣을껀데요

그 하나하나당 이미지를 넣을껀데 그 이미지에 사이즈가 최대사이즈가 얼마가 들어갈수있는건가요?


developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html


아래주소로 가보면 


30 x 30  이 기본이고 60 x 60 이 높은퀄리티인거 같은데...

탭바아이템 하나하나가 정사각형이 아니고 직사각형 모양인데...기준은 저렇게 적혀있어서

탭바를 4개 넣을시에 최대사이즈를 알고싶습니다..

76x48 정도로 잡아서 해봤었는데 이미지가 삽입되는데 아랫부분이 잘려서 들어가지더라구요...

(이것도 좀 의문입니다...분명 가로크기를 기준에서 벗어났는데 들어가진걸보면...)

도움좀 주세요~


Posted by 다오나무
영삼이의 IT정보2012. 6. 14. 12:29
Posted by 다오나무
영삼이의 IT정보2012. 6. 11. 18:14

아이폰(iPhone) 탭바 구현 - (3) (tabBar)에 아이콘과 색깔 넣기

 

개발환경 : Mac OS X 10.6.3, Simulator - 3.1.3

 

글보다는 그림(아이콘이 탭바에 들어가게 되면 보다 명확하게 어떤 기능을 하는

곳을 가리키는지 알려줄수 있어서 좋다하지만 단점이 있다일반 그림이 들어가게

되면 색깔정보(Opaque) 는 무시되고 이미지에 포함된 Alpha(투명색정보로만

표시가 된다그러니까 일반 그림을 넣게되면 형태만 나오게 된다.

테스트를 해보고 싶다면 투명색정보를 집어넣던지 아니면 투명색 정보가 있는

아이콘으로 해보면 될것이다색깔 쪽은 무지한 상태로 일단 넘어가기로 한다.

 

[원본그림]

[표현그림]

들어가는 이미지의 기본크기는 30x30 이다이에 맞지 않는다면 자동으로 확대/축소된다.

 

탭에 이미지를 넣고 싶다면 먼저 Resources 폴더에 쓸만한 아이콘을 집어넣는다.

그리고 MainWindow.xib 를 클릭해 인터페이스 빌더를 띄운다탭을 클릭하지 말고

표나 타이틀을 클릭하게 되면 그 부분만 선택되게 된다그 상태에서 Inspector 창의

Attributes 란을 보게 되면 아래쪽에 Image 라는 란이있다콤보를 클릭해서 보면

Resources 란에 집어넣었던 이미지가 다 나오게 되는데 이중 하나를 선택하면

표시가 되게 된다다른 탭도 마찬가지 과정을 거치면 된다.

3개의 탭에 모두 다른 그림을 집어넣고 실행한 화면이다어째 마음에 안들지만

Alpha 어쩌구 때문에 그렇다는건 알았기 때문에 그걸로 만족해야겠다

'영삼이의 IT정보' 카테고리의 다른 글

mac os x 에 apache module dav_svn 설치하기.  (0) 2012.06.12
맥용 SVN 서버 설치  (0) 2012.06.12
StoreKit  (0) 2012.06.10
iOS 키보드  (0) 2012.06.10
아이폰 OS 개발 자료 총정리  (2) 2012.06.04
Posted by 다오나무