1. 程式人生 > >自定義導航欄按鈕UIBarButtonItem 文字或圖片

自定義導航欄按鈕UIBarButtonItem 文字或圖片

在4.0裡定義導航條按鈕通常是生成普通按鈕,再用它生成導航條專用按鈕。

[java] view plaincopyprint?
  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. UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:menu];  
  8. self.navigationItem.rightBarButtonItem = menuButton;  
  9. [button release];  
  10. [menuButton release];  

如果是在導航條一邊建立多個button,在4.0裡是通過segmentcontrol來間接實現 [java] view plaincopyprint?
  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 plaincopyprint?
  1. - (void)segmentAction:(id)sender  
  2. {  
  3.     //NSLog(@"segmentAction: selected segment = %d", [sender selectedSegmentIndex]);
  4.     if ([sender selectedSegmentIndex] == 0) {  
  5.         //[self startAll];
  6.     }elseif ([sender selectedSegmentIndex] == 1) {  
  7.         //[self stopAll];
  8.     }  
  9. }  

在iOS 5.0中,導航條引入了新的方法 setLeftBarButtonItems:animated:和setRightBarButtonItems:animated:來直接定義左右側的多個button,方便了許多 [java] view plaincopyprint?
  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]];