自定義導航欄按鈕UIBarButtonItem 文字或圖片
阿新 • • 發佈:2019-01-24
在4.0裡定義導航條按鈕通常是生成普通按鈕,再用它生成導航條專用按鈕。
[java] view plaincopyprint?- UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
- [button setBackgroundImage:[UIImage imageNamed:@"button_main.png"]
- forState:UIControlStateNormal];
-
[button addTarget:self action:@selector
- forControlEvents:UIControlEventTouchUpInside];
- button.frame = CGRectMake(x, y, x1, x2);
- UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:menu];
- self.navigationItem.rightBarButtonItem = menuButton;
- [button release];
-
[menuButton release];
如果是在導航條一邊建立多個button,在4.0裡是通過segmentcontrol來間接實現 [java] view plaincopyprint?
- UISegmentedControl *SegmentedControl = [[UISegmentedControl alloc] initWithItems:
- [NSArray arrayWithObjects:
- @"開始",
-
@"暫停"
- [SegmentedControl addTarget:self action:@selector(segmentAction:)
- forControlEvents:UIControlEventValueChanged];
- SegmentedControl.frame = CGRectMake(0, 0, 80, 30);
- SegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
- SegmentedControl.momentary = YES;
- SegmentedControl.tintColor = [UIColor colorWithHue:0.6 saturation:0.33 brightness:0.69 alpha:0];
- //defaultTintColor = [segmentedControl.tintColor retain]; // keep track of this for later
- UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc]
- initWithCustomView:SegmentedControl];
- self.navigationItem.rightBarButtonItem = segmentBarItem;
之後 通過Action方法判斷是哪個button被按下 [java] view plaincopyprint?
- - (void)segmentAction:(id)sender
- {
- //NSLog(@"segmentAction: selected segment = %d", [sender selectedSegmentIndex]);
- if ([sender selectedSegmentIndex] == 0) {
- //[self startAll];
- }elseif ([sender selectedSegmentIndex] == 1) {
- //[self stopAll];
- }
- }
在iOS 5.0中,導航條引入了新的方法 setLeftBarButtonItems:animated:和setRightBarButtonItems:animated:來直接定義左右側的多個button,方便了許多 [java] view plaincopyprint?
- UIBarButtonItem *startBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startDownloadAll)];
- UIBarButtonItem *pauseBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(stopDownloadAll)];
- [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects: pauseBtn,startBtn,nil]];