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

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

 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 [button setBackgroundImage:[UIImage imageNamed:@"button_main.png"]
                                       forState:UIControlStateNormal];
 [button addTarget:self action:@selector(GotoSettings)
              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来间接实现

        UISegmentedControl *SegmentedControl = [[UISegmentedControl alloc] initWithItems:
                                                 [NSArray arrayWithObjects:
                                                  @"开始",
                                                  @"暂停", nil]];
        [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被按下

- (void)segmentAction:(id)sender
{
    
	//NSLog(@"segmentAction: selected segment = %d", [sender selectedSegmentIndex]);
    if ([sender selectedSegmentIndex] == 0) {
        //[self startAll];
        
    }else if ([sender selectedSegmentIndex] == 1) {
        //[self stopAll];
    }
    
}

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

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]];




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值