Iphone将window的跟视图替换成自定义的TabBar视图

来源:互联网 发布:手机app淘宝怎么投诉 编辑:程序博客网 时间:2024/06/01 19:53

转自:http://blog.csdn.net/RiverAM/article/details/7365070#comments

我们在项目中应该会遇到UINavigationController和UITabBarController不能同时存在于window视图,但是往往项目是这样的,先需要UINavigationController视图作为根视图(比如说登录界面,登录界面是不需要下面的tabbar的),然后登录进去后就需要一个UITabBarController视图,所以让人比较的纠结,下面将解决这个问题,先建一个基于Navigation的项目,项目会自动将UINavigationController加入window根视图中,然后在rootviewcontroller(自动生成的)页面中加入一个button,点击这个button后就会将window视图中的UINavigationController删除并将自定义的UITabBarController加入window根视图中,之所以要自定义UITabBarController,是因为自定义的东西样式背景等随便自己变,很方便,并且这些自定义的UITabBarController代码以后都可以重用的,修改的部分很少,当然你可以用iphone自带的UITabBarController:

1.建一个基于导航的项目,然后在RootViewController.h中将项目自动生成的delegate导入进来,在TraverNotepadForIphoneAppDelegate.m文件中将为下面定义的rootdelegate赋值:

[cpp] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2. #import "TraverNotepadForIphoneAppDelegate.h"  
  3. @class TraverNotepadForIphoneAppDelegate;  
  4. @interface RootViewController : UIViewController {  
  5.       
  6.     TraverNotepadForIphoneAppDelegate *rootdelegate;//项目委托  
  7. }  
  8.   
  9. @property(nonatomic,retain)TraverNotepadForIphoneAppDelegate *rootdelegate;  
  10. @end  

2. 在RootViewController.xib中添加一个UIButton,下面是这个button的点击事件的方法:

[cpp] view plaincopy
  1. -(IBAction)userregisterbutton{  
  2.     [self.rootdelegate.window addSubview:self.rootdelegate.mycustomtabbarview.view];  
  3.     [self.rootdelegate.navigationController.view removeFromSuperview];  
  4.   
  5. }  

3.下面的代码是自定义的UITabBarController以及自定义tabbar需要的另外两个文件:

先是新建一个继承于UIViewController的类,记得将自动生成xib文件的复选筐选上,两个文件的代码如下,这里面用到了几个类,这需要自己定义,知识当作测试而已,这里就没添出来了:

[cpp] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2. #import "CustomTabBar.h"  
  3.   
  4. @interface MyCustomTabBarViewController : UIViewController<CustomTabBarDelegate,UITabBarControllerDelegate> {  
  5.       CustomTabBar* tabBar;  
  6. }  
  7. @property (nonatomic, retain) CustomTabBar* tabBar;  
  8. @end  

[cpp] view plaincopy
  1. #import "MyCustomTabBarViewController.h"  
  2. #import "TraverHomeViewController.h"  
  3. #import "WelcomeViewController.h"  
  4.   
  5. @implementation MyCustomTabBarViewController  
  6.   
  7. #define SELECTED_VIEW_CONTROLLER_TAG 98456345  
  8. static NSArray* tabBarItems = nil;  
  9.   
  10.   
  11. @synthesize tabBar;  
  12.   
  13. - (void) awakeFromNib  
  14. {  
  15.     // Set up some fake view controllers each with a different background color so we can visually see the controllers getting swapped around  
  16.       
  17.     WelcomeViewController *browseCar = [[WelcomeViewController alloc] initWithNibName:@"WelcomeViewController" bundle:nil];  
  18.     browseCar.title= @"欢迎回来";  
  19.     //browseCar.formNavItem = browseCar.navigationItem;  
  20.       
  21.     UINavigationController *onectrlNav = [[UINavigationController alloc]initWithRootViewController:browseCar];  
  22.       
  23.       
  24.       
  25.     TraverHomeViewController *twoCtrl = [[TraverHomeViewController alloc] initWithNibName:@"TraverHomeViewController" bundle:nil];  
  26.     twoCtrl.title= @"旅行记事本";  
  27.       
  28.     UINavigationController *twoctrlNav = [[UINavigationController alloc]initWithRootViewController:twoCtrl];  
  29.       
  30.     TraverHomeViewController *accessoricesCtrl = [[TraverHomeViewController alloc] initWithNibName:@"TraverHomeViewController" bundle:nil];  
  31.     accessoricesCtrl.title= @"行程微博";  
  32.       
  33.     UINavigationController *threectrlNav = [[UINavigationController alloc]initWithRootViewController:accessoricesCtrl];  
  34.       
  35.     TraverHomeViewController *fourCtrl = [[TraverHomeViewController alloc] initWithNibName:@"TraverHomeViewController" bundle:nil];  
  36.     fourCtrl.title= @"行程计划";  
  37.       
  38.     UINavigationController *fourctrlNav = [[UINavigationController alloc]initWithRootViewController:fourCtrl];  
  39.       
  40.     TraverHomeViewController *fiveCtrl = [[TraverHomeViewController alloc] initWithNibName:@"TraverHomeViewController" bundle:nil];  
  41.     fiveCtrl.title= @"查询旅游产品";  
  42.       
  43.     UINavigationController *fivectrlNav = [[UINavigationController alloc]initWithRootViewController:fiveCtrl];  
  44.       
  45.     TraverHomeViewController *sixCtrl = [[TraverHomeViewController alloc] initWithNibName:@"TraverHomeViewController" bundle:nil];  
  46.     sixCtrl.title= @"设置";  
  47.       
  48.     UINavigationController *sixctrlNav = [[UINavigationController alloc]initWithRootViewController:sixCtrl];  
  49.       
  50.       
  51.     tabBarItems = [[NSArray arrayWithObjects:  
  52.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", onectrlNav, @"viewController", nil],  
  53.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", twoctrlNav, @"viewController", nil],  
  54.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", threectrlNav, @"viewController", nil],  
  55.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", fourctrlNav, @"viewController", nil],  
  56.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", fivectrlNav,  
  57.                      @"viewController", nil],  
  58.                     [NSDictionary dictionaryWithObjectsAndKeys:@"chat.png", @"image", sixctrlNav,  
  59.                      @"viewController", nil],nil] retain];  
  60.       
  61.       
  62.     [browseCar release];  
  63.     [twoCtrl release];  
  64.     [accessoricesCtrl release];  
  65.     [fourCtrl release];  
  66.     [fiveCtrl release];  
  67.     [sixCtrl release];  
  68.       
  69.     [onectrlNav release];  
  70.     [twoctrlNav release];  
  71.     [threectrlNav release];  
  72.     [fourctrlNav release];  
  73.     [fivectrlNav release];  
  74.     [sixctrlNav release];  
  75. }  
  76.   
  77.   
  78. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  79. {  
  80.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  81.     if (self) {  
  82.         // Custom initialization  
  83.     }  
  84.     return self;  
  85. }  
  86.   
  87. - (void)dealloc  
  88. {  
  89.     [tabBar release];  
  90.     [super dealloc];  
  91. }  
  92.   
  93. - (void)didReceiveMemoryWarning  
  94. {  
  95.     // Releases the view if it doesn't have a superview.  
  96.     [super didReceiveMemoryWarning];  
  97.       
  98.     // Release any cached data, images, etc that aren't in use.  
  99. }  
  100.   
  101. #pragma mark - View lifecycle  
  102.   
  103. - (void)viewDidLoad  
  104. {  
  105.     [super viewDidLoad];  
  106.     // Do any additional setup after loading the view from its nib.  
  107.     // Use the TabBarGradient image to figure out the tab bar's height (22x2=44)  
  108.     UIImage* tabBarGradient = [UIImage imageNamed:@"TabBarGradient.png"];  
  109.       
  110.     // Create a custom tab bar passing in the number of items, the size of each item and setting ourself as the delegate  
  111.     self.tabBar = [[[CustomTabBar alloc] initWithItemCount:tabBarItems.count itemSize:CGSizeMake(self.view.frame.size.width/tabBarItems.count, tabBarGradient.size.height*2-4) tag:0 delegate:self] autorelease];  
  112.       
  113.     // Place the tab bar at the bottom of our view  
  114.     tabBar.frame = CGRectMake(0,self.view.frame.size.height-(tabBarGradient.size.height*2),self.view.frame.size.width, tabBarGradient.size.height*2+20);  
  115.     [self.view addSubview:tabBar];  
  116.       
  117.     // Select the first tab  
  118.     [tabBar selectItemAtIndex:0];  
  119.     [self touchDownAtItemAtIndex:0];  
  120. }  
  121.   
  122. #pragma mark -  
  123. #pragma mark CustomTabBarDelegate  
  124.   
  125. - (UIImage*) imageFor:(CustomTabBar*)tabBar atIndex:(NSUInteger)itemIndex  
  126. {  
  127.     // Get the right data  
  128.     NSDictionary* data = [tabBarItems objectAtIndex:itemIndex];  
  129.     // Return the image for this tab bar item  
  130.     return [UIImage imageNamed:[data objectForKey:@"image"]];  
  131. }  
  132.   
  133. - (UIImage*) backgroundImage  
  134. {  
  135.     // The tab bar's width is the same as our width  
  136.     CGFloat width = self.view.frame.size.width;  
  137.     // Get the image that will form the top of the background  
  138.     UIImage* topImage = [UIImage imageNamed:@"TabBarGradient.png"];  
  139.       
  140.     // Create a new image context  
  141.     UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, topImage.size.height*2), NO, 0.0);  
  142.       
  143.     // Create a stretchable image for the top of the background and draw it  
  144.     UIImage* stretchedTopImage = [topImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];  
  145.     [stretchedTopImage drawInRect:CGRectMake(0, 0, width, topImage.size.height)];  
  146.       
  147.     // Draw a solid black color for the bottom of the background  
  148.     [[UIColor blackColor] set];  
  149.     CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, topImage.size.height, width, topImage.size.height));  
  150.       
  151.     // Generate a new image  
  152.     UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();  
  153.     UIGraphicsEndImageContext();  
  154.       
  155.     return resultImage;  
  156. }  
  157.   
  158. // This is the blue background shown for selected tab bar items  
  159. - (UIImage*) selectedItemBackgroundImage  
  160. {  
  161.     return [UIImage imageNamed:@"TabBarItemSelectedBackground.png"];  
  162. }  
  163.   
  164. // This is the glow image shown at the bottom of a tab bar to indicate there are new items  
  165. - (UIImage*) glowImage  
  166. {  
  167.     UIImage* tabBarGlow = [UIImage imageNamed:@"TabBarGlow.png"];  
  168.       
  169.     // Create a new image using the TabBarGlow image but offset 4 pixels down  
  170.     UIGraphicsBeginImageContextWithOptions(CGSizeMake(tabBarGlow.size.width, tabBarGlow.size.height-4.0), NO, 0.0);  
  171.       
  172.     // Draw the image  
  173.     [tabBarGlow drawAtPoint:CGPointZero];  
  174.       
  175.     // Generate a new image  
  176.     UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();  
  177.     UIGraphicsEndImageContext();  
  178.       
  179.     return resultImage;  
  180. }  
  181.   
  182. // This is the embossed-like image shown around a selected tab bar item  
  183. - (UIImage*) selectedItemImage  
  184. {  
  185.     // Use the TabBarGradient image to figure out the tab bar's height (22x2=44)  
  186.     UIImage* tabBarGradient = [UIImage imageNamed:@"TabBarGradient.png"];  
  187.     CGSize tabBarItemSize = CGSizeMake(self.view.frame.size.width/tabBarItems.count, tabBarGradient.size.height*2);  
  188.     UIGraphicsBeginImageContextWithOptions(tabBarItemSize, NO, 0.0);  
  189.       
  190.     // Create a stretchable image using the TabBarSelection image but offset 4 pixels down  
  191.     [[[UIImage imageNamed:@"TabBarSelection.png"] stretchableImageWithLeftCapWidth:4.0 topCapHeight:0] drawInRect:CGRectMake(0, 4.0, tabBarItemSize.width, tabBarItemSize.height-4.0)];    
  192.       
  193.     // Generate a new image  
  194.     UIImage* selectedItemImage = UIGraphicsGetImageFromCurrentImageContext();  
  195.     UIGraphicsEndImageContext();  
  196.       
  197.     return selectedItemImage;  
  198. }  
  199.   
  200. - (UIImage*) tabBarArrowImage  
  201. {  
  202.     return [UIImage imageNamed:@"TabBarNipple.png"];  
  203. }  
  204.   
  205. - (void) touchDownAtItemAtIndex:(NSUInteger)itemIndex  
  206. {  
  207.       
  208.     [self awakeFromNib];// 重新给每个item指定view,保证每次点击都是同一个页面  
  209.       
  210.       
  211.     // Remove the current view controller's view  
  212.     UIView* currentView = [self.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];  
  213.     [currentView removeFromSuperview];  
  214.       
  215.     // Get the right view controller  
  216.     NSDictionary* data = [tabBarItems objectAtIndex:itemIndex];  
  217.     UIViewController* viewController = [data objectForKey:@"viewController"];  
  218.       
  219.     // Use the TabBarGradient image to figure out the tab bar's height (22x2=44)  
  220.     UIImage* tabBarGradient = [UIImage imageNamed:@"TabBarGradient.png"];  
  221.       
  222.     // Set the view controller's frame to account for the tab bar  
  223.     viewController.view.frame = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height-(tabBarGradient.size.height*2));  
  224.       
  225.     // Se the tag so we can find it later  
  226.     viewController.view.tag = SELECTED_VIEW_CONTROLLER_TAG;  
  227.       
  228.       
  229.         // Add the new view controller's view  
  230.     [self.view insertSubview:viewController.view belowSubview:tabBar];  
  231.      // UIView* currentView2 = [self.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];    
  232.    // NSLog(@"=====%d",[self.navigationController.view.subviews count]);  
  233.       //  [currentView2 removeFromSuperview];  
  234.     //[self.navigationController popViewControllerAnimated:YES];  
  235.   
  236.     // In 1 second glow the selected tab  
  237.     [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(addGlowTimerFireMethod:) userInfo:[NSNumber numberWithInteger:itemIndex] repeats:NO];  
  238.       
  239. }  
  240.   
  241. - (void)addGlowTimerFireMethod:(NSTimer*)theTimer  
  242. {  
  243.     // Remove the glow from all tab bar items  
  244.     for (NSUInteger i = 0 ; i < tabBarItems.count ; i++)  
  245.     {  
  246.         [tabBar removeGlowAtIndex:i];  
  247.     }  
  248.       
  249.     // Then add it to this tab bar item  
  250.     [tabBar glowItemAtIndex:[[theTimer userInfo] integerValue]];  
  251. }  
  252.   
  253.   
  254. - (void)viewDidUnload  
  255. {  
  256.     [super viewDidUnload];  
  257.     // Release any retained subviews of the main view.  
  258.     // e.g. self.myOutlet = nil;  
  259. }  
  260.   
  261. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  262. {  
  263.     // Return YES for supported orientations  
  264.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  265. }  
  266.   
  267. @end  

然后是新建一个继承于UIView的类,这是自定义tabar的工具类,代码如下:

[cpp] view plaincopy
  1. @class CustomTabBar;  
  2. @protocol CustomTabBarDelegate  
  3.   
  4. - (UIImage*) imageFor:(CustomTabBar*)tabBar atIndex:(NSUInteger)itemIndex;  
  5. - (UIImage*) backgroundImage;  
  6. - (UIImage*) selectedItemBackgroundImage;  
  7. - (UIImage*) glowImage;  
  8. - (UIImage*) selectedItemImage;  
  9. - (UIImage*) tabBarArrowImage;  
  10.   
  11. @optional  
  12. - (void) touchUpInsideItemAtIndex:(NSUInteger)itemIndex;  
  13. - (void) touchDownAtItemAtIndex:(NSUInteger)itemIndex;  
  14. @end  
  15.   
  16.   
  17. @interface CustomTabBar : UIView  
  18. {  
  19.   NSObject <CustomTabBarDelegate> *delegate;  
  20.   NSMutableArray* buttons;  
  21.   NSArray *titles;  
  22. }  
  23.   
  24. @property (nonatomic, retain) NSMutableArray* buttons;  
  25. @property (nonatomic, retain)  NSArray *titles;  
  26.   
  27. - (id) initWithItemCount:(NSUInteger)itemCount itemSize:(CGSize)itemSize tag:(NSInteger)objectTag delegate:(NSObject <CustomTabBarDelegate>*)customTabBarDelegate;  
  28.   
  29. - (void) selectItemAtIndex:(NSInteger)index;  
  30. - (void) glowItemAtIndex:(NSInteger)index;  
  31. - (void) removeGlowAtIndex:(NSInteger)index;  
  32.   
  33. @end  

[cpp] view plaincopy
  1. #import "CustomTabBar.h"  
  2.   
  3. #define GLOW_IMAGE_TAG 2394858  
  4. #define TAB_ARROW_IMAGE_TAG 2394859  
  5.   
  6. @interface CustomTabBar (PrivateMethods)  
  7. - (CGFloat) horizontalLocationFor:(NSUInteger)tabIndex;  
  8. - (void) addTabBarArrowAtIndex:(NSUInteger)itemIndex;  
  9. -(UIButton*) buttonAtIndex:(NSUInteger)itemIndex width:(CGFloat)width;  
  10. -(UIImage*) tabBarImage:(UIImage*)startImage size:(CGSize)targetSize backgroundImage:(UIImage*)backgroundImage;  
  11. -(UIImage*) blackFilledImageWithWhiteBackgroundUsing:(UIImage*)startImage;  
  12. -(UIImage*) tabBarBackgroundImageWithSize:(CGSize)targetSize backgroundImage:(UIImage*)backgroundImage;  
  13. @end  
  14.   
  15. @implementation CustomTabBar  
  16. @synthesize buttons;  
  17. @synthesize titles;  
  18.   
  19. - (id) initWithItemCount:(NSUInteger)itemCount itemSize:(CGSize)itemSize tag:(NSInteger)objectTag delegate:(NSObject <CustomTabBarDelegate>*)customTabBarDelegate  
  20. {  
  21.     self = [super init];  
  22.   if (self)  
  23.   {  
  24.     // The tag allows callers withe multiple controls to distinguish between them  
  25.     self.tag = objectTag;  
  26.       
  27.     // Set the delegate  
  28.     delegate = customTabBarDelegate;  
  29.       self.titles = [[NSArray alloc] initWithObjects:@"欢迎回来",@"旅行记事本",@"行程微博",@"行程计划",@"查询旅游产品",@"设置",nil];  
  30.     // Add the background image  
  31.     UIImage* backgroundImage = [delegate backgroundImage];  
  32.     UIImageView* backgroundImageView = [[[UIImageView alloc] initWithImage:backgroundImage] autorelease];  
  33.     backgroundImageView.frame = CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height);  
  34.     [self addSubview:backgroundImageView];  
  35.   
  36.     // Adjust our width based on the number of items & the width of each item  
  37.     self.frame = CGRectMake(0, 0, itemSize.width * itemCount, itemSize.height);  
  38.   
  39.     // Initalize the array we use to store our buttons  
  40.     self.buttons = [[NSMutableArray alloc] initWithCapacity:itemCount];  
  41.   
  42.     // horizontalOffset tracks the proper x value as we add buttons as subviews  
  43.     CGFloat horizontalOffset = 0;  
  44.       
  45.     // Iterate through each item  
  46.     for (NSUInteger i = 0 ; i < itemCount ; i++)  
  47.     {  
  48.       // Create a button  
  49.       UIButton* button = [self buttonAtIndex:i width:self.frame.size.width/itemCount];  
  50.   
  51.       // Register for touch events  
  52.       [button addTarget:self action:@selector(touchDownAction:) forControlEvents:UIControlEventTouchDown];  
  53.       [button addTarget:self action:@selector(touchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];  
  54.       [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchUpOutside];  
  55.       [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragOutside];  
  56.       [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragInside];  
  57.         
  58.       // Add the button to our buttons array  
  59.       [buttons addObject:button];  
  60.   
  61.       // Set the button's x offset  
  62.         button.frame = CGRectMake(horizontalOffset, 0.0, button.frame.size.width, button.frame.size.height);  
  63.         
  64.         NSString *titls = [self.titles objectAtIndex:i];  
  65.           
  66.         CGSize titleSize = [titls sizeWithFont:[UIFont boldSystemFontOfSize:10.0] constrainedToSize:CGSizeMake(MAXFLOAT,30)];  
  67.           
  68.       //添加底部的文字  
  69.         UILabel *myLabel = [[[UILabel alloc] initWithFrame: CGRectMake(button.frame.size.width/2.0 -titleSize.width/2, button.frame.origin.y + button.frame.size.height - 10, button.frame.size.width, titleSize.height)] autorelease];  
  70.         
  71.         [myLabel setTextColor: [UIColor whiteColor]];  
  72.         myLabel.text =  [self.titles objectAtIndex:i];  
  73.         myLabel.font = [UIFont boldSystemFontOfSize:10.0];  
  74.         myLabel.lineBreakMode = UILineBreakModeWordWrap;  
  75.         myLabel.numberOfLines = 4;  
  76.         [myLabel setBackgroundColor:[UIColor clearColor]];  
  77.           
  78.         [button addSubview:myLabel];  
  79.           
  80.       // Add the button as our subview  
  81.       [self addSubview:button];  
  82.           
  83.       // Advance the horizontal offset  
  84.       horizontalOffset = horizontalOffset + itemSize.width;  
  85.     }  
  86.   }  
  87.   
  88.   return self;  
  89. }  
  90.   
  91. -(void) dimAllButtonsExcept:(UIButton*)selectedButton  
  92. {  
  93.   for (UIButton* button in buttons)  
  94.   {  
  95.     if (button == selectedButton)  
  96.     {  
  97.       button.selected = YES;  
  98.       button.highlighted = button.selected ? NO : YES;  
  99.   
  100.       UIImageView* tabBarArrow = (UIImageView*)[self viewWithTag:TAB_ARROW_IMAGE_TAG];  
  101.       NSUInteger selectedIndex = [buttons indexOfObjectIdenticalTo:button];  
  102.       if (tabBarArrow)  
  103.       {  
  104.         [UIView beginAnimations:nil context:nil];  
  105.         [UIView setAnimationDuration:0.2];  
  106.         CGRect frame = tabBarArrow.frame;  
  107.         frame.origin.x = [self horizontalLocationFor:selectedIndex];  
  108.         tabBarArrow.frame = frame;  
  109.         [UIView commitAnimations];  
  110.       }  
  111.       else  
  112.       {  
  113.         [self addTabBarArrowAtIndex:selectedIndex];  
  114.       }  
  115.     }  
  116.     else  
  117.     {  
  118.       button.selected = NO;  
  119.       button.highlighted = NO;  
  120.     }  
  121.   }  
  122. }  
  123.   
  124. - (void)touchDownAction:(UIButton*)button  
  125. {  
  126.   [self dimAllButtonsExcept:button];  
  127.     
  128.   if ([delegate respondsToSelector:@selector(touchDownAtItemAtIndex:)])  
  129.     [delegate touchDownAtItemAtIndex:[buttons indexOfObject:button]];  
  130. }  
  131.   
  132. - (void)touchUpInsideAction:(UIButton*)button  
  133. {  
  134.   [self dimAllButtonsExcept:button];  
  135.   
  136.   if ([delegate respondsToSelector:@selector(touchUpInsideItemAtIndex:)])  
  137.     [delegate touchUpInsideItemAtIndex:[buttons indexOfObject:button]];  
  138. }  
  139.   
  140. - (void)otherTouchesAction:(UIButton*)button  
  141. {  
  142.   [self dimAllButtonsExcept:button];  
  143. }  
  144.   
  145. - (void) selectItemAtIndex:(NSInteger)index  
  146. {  
  147.   // Get the right button to select  
  148.   UIButton* button = [buttons objectAtIndex:index];  
  149.     
  150.   [self dimAllButtonsExcept:button];  
  151. }  
  152.   
  153. // Add a glow at the bottom of the specified item  
  154. - (void) glowItemAtIndex:(NSInteger)index  
  155. {  
  156.   // Get the right button. We'll use to calculate where to put the glow  
  157.   UIButton* button = [buttons objectAtIndex:index];  
  158.     
  159.   // Ask the delegate for the glow image  
  160.   UIImage* glowImage = [delegate glowImage];  
  161.     
  162.   // Create the image view that will hold the glow image  
  163.   UIImageView* glowImageView = [[[UIImageView alloc] initWithImage:glowImage] autorelease];  
  164.     
  165.   // Center the glow image at the center of the button horizontally and at the bottom of the button vertically  
  166.   glowImageView.frame = CGRectMake(button.frame.size.width/2.0 - glowImage.size.width/2.0, button.frame.origin.y + button.frame.size.height - glowImage.size.height, glowImage.size.width, glowImage.size.height);  
  167.   
  168.   // Set the glow image view's tag so we can find it later when we want to remove the glow  
  169.   glowImageView.tag = GLOW_IMAGE_TAG;  
  170.     
  171.   // Add the glow image view to the button  
  172.     //去掉灯光的效果  
  173.   //[button addSubview:glowImageView];  
  174. }  
  175.   
  176. // Remove the glow at the bottom of the specified item  
  177. - (void) removeGlowAtIndex:(NSInteger)index  
  178. {  
  179.   // Find the right button  
  180.   UIButton* button = [buttons objectAtIndex:index];  
  181.   // Find the glow image view  
  182.   UIImageView* glowImageView = (UIImageView*)[button viewWithTag:GLOW_IMAGE_TAG];  
  183.   // Remove it from the button  
  184.   [glowImageView removeFromSuperview];  
  185. }  
  186.   
  187. - (CGFloat) horizontalLocationFor:(NSUInteger)tabIndex  
  188. {  
  189.   UIImageView* tabBarArrow = (UIImageView*)[self viewWithTag:TAB_ARROW_IMAGE_TAG];  
  190.     
  191.   // A single tab item's width is the entire width of the tab bar divided by number of items  
  192.   CGFloat tabItemWidth = self.frame.size.width / buttons.count;  
  193.   // A half width is tabItemWidth divided by 2 minus half the width of the arrow  
  194.   CGFloat halfTabItemWidth = (tabItemWidth / 2.0) - (tabBarArrow.frame.size.width / 2.0);  
  195.     
  196.   // The horizontal location is the index times the width plus a half width  
  197.   return (tabIndex * tabItemWidth) + halfTabItemWidth;  
  198. }  
  199.   
  200. - (void) addTabBarArrowAtIndex:(NSUInteger)itemIndex  
  201. {  
  202.   UIImage* tabBarArrowImage = [delegate tabBarArrowImage];  
  203.   UIImageView* tabBarArrow = [[[UIImageView alloc] initWithImage:tabBarArrowImage] autorelease];  
  204.   tabBarArrow.tag = TAB_ARROW_IMAGE_TAG;  
  205.   // To get the vertical location we go up by the height of arrow and then come back down 2 pixels so the arrow is slightly on top of the tab bar.  
  206.   CGFloat verticalLocation = -tabBarArrowImage.size.height + 2;  
  207.   tabBarArrow.frame = CGRectMake([self horizontalLocationFor:itemIndex], verticalLocation, tabBarArrowImage.size.width, tabBarArrowImage.size.height);  
  208.   
  209.   [self addSubview:tabBarArrow];  
  210. }  
  211.   
  212. // Create a button at the provided index  
  213. - (UIButton*) buttonAtIndex:(NSUInteger)itemIndex width:(CGFloat)width  
  214. {  
  215.   // Create a new button with the right dimensions  
  216.   UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];  
  217.   button.frame = CGRectMake(0.0, 0.0, width, self.frame.size.height);  
  218.   
  219.   // Ask the delegate for the button's image  
  220.   UIImage* rawButtonImage = [delegate imageFor:self atIndex:itemIndex];  
  221.   // Create the normal state image by converting the image's background to gray  
  222.   UIImage* buttonImage = [self tabBarImage:rawButtonImage size:button.frame.size backgroundImage:nil];  
  223.   // And create the pressed state image by converting the image's background to the background image we get from the delegate  
  224.   UIImage* buttonPressedImage = [self tabBarImage:rawButtonImage size:button.frame.size backgroundImage:[delegate selectedItemBackgroundImage]];  
  225.   
  226.   // Set the gray & blue images as the button states  
  227.   [button setImage:buttonImage forState:UIControlStateNormal];  
  228.   [button setImage:buttonPressedImage forState:UIControlStateHighlighted];  
  229.   [button setImage:buttonPressedImage forState:UIControlStateSelected];  
  230.   
  231.   // Ask the delegate for the highlighted/selected state image & set it as the selected background state  
  232.   [button setBackgroundImage:[delegate selectedItemImage] forState:UIControlStateHighlighted];  
  233.   [button setBackgroundImage:[delegate selectedItemImage] forState:UIControlStateSelected];  
  234.     
  235.   button.adjustsImageWhenHighlighted = NO;  
  236.     
  237.   return button;  
  238. }  
  239.   
  240. // Create a tab bar image  
  241. -(UIImage*) tabBarImage:(UIImage*)startImage size:(CGSize)targetSize backgroundImage:(UIImage*)backgroundImageSource  
  242. {  
  243.   // The background is either the passed in background image (for the blue selected state) or gray (for the non-selected state)  
  244.   UIImage* backgroundImage = [self tabBarBackgroundImageWithSize:startImage.size backgroundImage:backgroundImageSource];  
  245.     
  246.   // Convert the passed in image to a white backround image with a black fill  
  247.   UIImage* bwImage = [self blackFilledImageWithWhiteBackgroundUsing:startImage];  
  248.     
  249.   // Create an image mask  
  250.   CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(bwImage.CGImage),  
  251.     CGImageGetHeight(bwImage.CGImage),  
  252.     CGImageGetBitsPerComponent(bwImage.CGImage),  
  253.     CGImageGetBitsPerPixel(bwImage.CGImage),  
  254.     CGImageGetBytesPerRow(bwImage.CGImage),  
  255.     CGImageGetDataProvider(bwImage.CGImage), NULL, YES);  
  256.   
  257.   // Using the mask create a new image  
  258.   CGImageRef tabBarImageRef = CGImageCreateWithMask(backgroundImage.CGImage, imageMask);  
  259.   
  260.   UIImage* tabBarImage = [UIImage imageWithCGImage:tabBarImageRef scale:startImage.scale orientation:startImage.imageOrientation];  
  261.   
  262.   // Cleanup  
  263.   CGImageRelease(imageMask);  
  264.   CGImageRelease(tabBarImageRef);  
  265.     
  266.   // Create a new context with the right size  
  267.   UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);  
  268.   
  269.   // Draw the new tab bar image at the center  
  270.   [tabBarImage drawInRect:CGRectMake((targetSize.width/2.0) - (startImage.size.width/2.0), (targetSize.height/2.0) - (startImage.size.height/2.0), startImage.size.width, startImage.size.height)];  
  271.     
  272.   // Generate a new image  
  273.   UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();  
  274.   UIGraphicsEndImageContext();  
  275.     
  276.   return resultImage;  
  277. }  
  278.   
  279. // Convert the image's fill color to black and background to white  
  280. -(UIImage*) blackFilledImageWithWhiteBackgroundUsing:(UIImage*)startImage  
  281. {  
  282.   // Create the proper sized rect  
  283.   CGRect imageRect = CGRectMake(0, 0, CGImageGetWidth(startImage.CGImage), CGImageGetHeight(startImage.CGImage));  
  284.   
  285.   // Create a new bitmap context  
  286.   CGContextRef context = CGBitmapContextCreate(NULL, imageRect.size.width, imageRect.size.height, 8, 0, CGImageGetColorSpace(startImage.CGImage), kCGImageAlphaPremultipliedLast);  
  287.   
  288.   CGContextSetRGBFillColor(context, 1, 1, 1, 1);  
  289.   CGContextFillRect(context, imageRect);  
  290.   
  291.   // Use the passed in image as a clipping mask  
  292.   CGContextClipToMask(context, imageRect, startImage.CGImage);  
  293.   // Set the fill color to black: R:0 G:0 B:0 alpha:1  
  294.   CGContextSetRGBFillColor(context, 0, 0, 0, 1);  
  295.   // Fill with black  
  296.   CGContextFillRect(context, imageRect);  
  297.   
  298.   // Generate a new image  
  299.   CGImageRef newCGImage = CGBitmapContextCreateImage(context);  
  300.   UIImage* newImage = [UIImage imageWithCGImage:newCGImage scale:startImage.scale orientation:startImage.imageOrientation];  
  301.   
  302.   // Cleanup  
  303.   CGContextRelease(context);  
  304.   CGImageRelease(newCGImage);  
  305.     
  306.   return newImage;  
  307. }  
  308.   
  309. -(UIImage*) tabBarBackgroundImageWithSize:(CGSize)targetSize backgroundImage:(UIImage*)backgroundImage  
  310. {  
  311.   // The background is either the passed in background image (for the blue selected state) or gray (for the non-selected state)  
  312.   UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);  
  313.   if (backgroundImage)  
  314.   {  
  315.     // Draw the background image centered  
  316.     [backgroundImage drawInRect:CGRectMake((targetSize.width - CGImageGetWidth(backgroundImage.CGImage)) / 2, (targetSize.height - CGImageGetHeight(backgroundImage.CGImage)) / 2, CGImageGetWidth(backgroundImage.CGImage), CGImageGetHeight(backgroundImage.CGImage))];  
  317.   }  
  318.   else  
  319.   {  
  320.     [[UIColor lightGrayColor] set];  
  321.     UIRectFill(CGRectMake(0, 0, targetSize.width, targetSize.height));  
  322.   }  
  323.   
  324.   UIImage* finalBackgroundImage = UIGraphicsGetImageFromCurrentImageContext();  
  325.   UIGraphicsEndImageContext();  
  326.     
  327.   return finalBackgroundImage;  
  328. }  
  329.   
  330. - (void)dealloc  
  331. {  
  332.   [super dealloc];  
  333.   [buttons release];  
  334.   [titles release];  
  335. }  
  336.   
  337.   
  338. @end  

4.在自动生成的TraverNotepadForIphoneAppDelegate类中添加如下代码:

TraverNotepadForIphoneAppDelegate.h文件:

[cpp] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2. #import "MyCustomTabBarViewController.h"  
  3. #import "RootViewController.h"  
  4. @class RootViewController;  
  5. @interface TraverNotepadForIphoneAppDelegate : NSObject <UIApplicationDelegate> {  
  6.     RootViewController *myrootview;//第一个页面  
  7.   
  8.      MyCustomTabBarViewController *mycustomtabbarview;//自定义的tabBar  
  9. }  
  10.   
  11. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  12.   
  13. @property (nonatomic, retain) IBOutlet UINavigationController *navigationController;  
  14.   
  15. @property (nonatomic, retain)   IBOutlet RootViewController *myrootview;  
  16.   
  17. @property(nonatomic,retain)IBOutlet MyCustomTabBarViewController *mycustomtabbarview;  
  18.   
  19. @end  
TraverNotepadForIphoneAppDelegate.m文件:

[cpp] view plaincopy
  1. #import "TraverNotepadForIphoneAppDelegate.h"  
  2.   
  3. @implementation TraverNotepadForIphoneAppDelegate  
  4.   
  5.   
  6. @synthesize window=_window;  
  7. @synthesize myrootview;  
  8. @synthesize mycustomtabbarview;  
  9. @synthesize navigationController=_navigationController;  
  10.   
  11. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  12. {  
  13.     // Override point for customization after application launch.  
  14.     // Add the navigation controller's view to the window and display.  
  15.     myrootview.rootdelegate = self;//将委托赋值  
  16.     self.window.rootViewController = self.navigationController;  
  17.     [self.window makeKeyAndVisible];  
  18.     return YES;  
  19. }  
  20.   
  21. - (void)applicationWillResignActive:(UIApplication *)application  
  22. {  
  23.     /* 
  24.      Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
  25.      Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
  26.      */  
  27. }  
  28.   
  29. - (void)applicationDidEnterBackground:(UIApplication *)application  
  30. {  
  31.     /* 
  32.      Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
  33.      If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
  34.      */  
  35. }  
  36.   
  37. - (void)applicationWillEnterForeground:(UIApplication *)application  
  38. {  
  39.     /* 
  40.      Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
  41.      */  
  42. }  
  43.   
  44. - (void)applicationDidBecomeActive:(UIApplication *)application  
  45. {  
  46.     /* 
  47.      Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
  48.      */  
  49. }  
  50.   
  51. - (void)applicationWillTerminate:(UIApplication *)application  
  52. {  
  53.     /* 
  54.      Called when the application is about to terminate. 
  55.      Save data if appropriate. 
  56.      See also applicationDidEnterBackground:. 
  57.      */  
  58. }  
  59.   
  60. - (void)dealloc  
  61. {  
  62.     [_window release];  
  63.     [_navigationController release];  
  64.     [myrootview release];  
  65.     [mycustomtabbarview release];  
  66.     [super dealloc];  
  67. }  
  68.   
  69. @end  

5.最后记得在MainWindow.xib中拖入一个View Controller,并将其class指定为MyCustomTabBarViewController,然后将该View Controller与

TraverNotepadForIphoneAppDelegate类中的mycustomtabbarview连接,并将TraverNotepadForIphoneAppDelegate类中的myrootview与MainWindow.xib中的RootViewController连接。


原创粉丝点击