自定义导航栏按钮UIBarButtonItem 文字或图片

在4.0里定义导航条按钮通常是生成普通按钮,再用它生成导航条专用按钮。

[java]  view plain copy print ?
  1. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
  2. [button setBackgroundImage:[UIImage imageNamed:@"button_main.png"]  
  3.                                       forState:UIControlStateNormal];  
  4. [button addTarget:self action:@selector(GotoSettings)  
  5.              forControlEvents:UIControlEventTouchUpInside];  
  6. button.frame = CGRectMake(x, y, x1, x2);  
  7.   
  8. UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:menu];  
  9. self.navigationItem.rightBarButtonItem = menuButton;  
  10.   
  11. [button release];  
  12. [menuButton release];  

如果是在导航条一边创建多个button,在4.0里是通过segmentcontrol来间接实现

[java]  view plain copy print ?
  1. UISegmentedControl *SegmentedControl = [[UISegmentedControl alloc] initWithItems:  
  2.                                          [NSArray arrayWithObjects:  
  3.                                           @"开始",  
  4.                                           @"暂停", nil]];  
  5. [SegmentedControl addTarget:self action:@selector(segmentAction:)   
  6.             forControlEvents:UIControlEventValueChanged];  
  7. SegmentedControl.frame = CGRectMake(008030);  
  8. SegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;  
  9. SegmentedControl.momentary = YES;  
  10. SegmentedControl.tintColor = [UIColor colorWithHue:0.6 saturation:0.33 brightness:0.69 alpha:0];  
  11. //defaultTintColor = [segmentedControl.tintColor retain];    // keep track of this for later  
  12. UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc]   
  13.                                        initWithCustomView:SegmentedControl];  
  14. self.navigationItem.rightBarButtonItem = segmentBarItem;  

之后 通过Action方法判断是哪个button被按下

[java]  view plain copy print ?
  1. - (void)segmentAction:(id)sender  
  2. {  
  3.       
  4.     //NSLog(@"segmentAction: selected segment = %d", [sender selectedSegmentIndex]);  
  5.     if ([sender selectedSegmentIndex] == 0) {  
  6.         //[self startAll];  
  7.           
  8.     }else if ([sender selectedSegmentIndex] == 1) {  
  9.         //[self stopAll];  
  10.     }  
  11.       
  12. }  

在iOS 5.0中,导航条引入了新的方法 setLeftBarButtonItems:animated:和setRightBarButtonItems:animated:来直接定义左右侧的多个button,方便了许多

[java]  view plain copy print ?
  1. UIBarButtonItem *startBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startDownloadAll)];  
  2. UIBarButtonItem *pauseBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(stopDownloadAll)];  
  3. [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects: pauseBtn,startBtn,nil]]; 

你可能感兴趣的:(自定义导航栏按钮UIBarButtonItem 文字或图片)