在ios中自定义导航栏

时间:2014-09-19 06:58:06

标签: ios objective-c iphone xcode uinavigationcontroller

我使用了导航控制器& StroryBoard 中的导航栏。

我想为导航栏右侧的一个视图自定义导航栏。

enter image description here

我尝试过的代码

    UIButton *btn_list=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_list.frame=CGRectMake(0, 0, 60, 30);
    [btn_list setTitle:@"Liste" forState:UIControlStateNormal];
    [btn_list setBackgroundImage:[UIImage imageNamed:@"red-left.png"] forState:UIControlStateNormal];
    [btn_list setBackgroundImage:[UIImage imageNamed:@"black-left.png"] forState:UIControlStateSelected];
    UIBarButtonItem *list_bar=[[UIBarButtonItem alloc]initWithCustomView:btn_list];

    UIButton *btn_map=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_map.frame=CGRectMake(0, 0, 60, 30);
    [btn_map setTitle:@"Karte" forState:UIControlStateNormal];
    [btn_map setBackgroundImage:[UIImage imageNamed:@"red-right.png"] forState:UIControlStateNormal];
    [btn_list setBackgroundImage:[UIImage imageNamed:@"black-right.png"] forState:UIControlStateSelected];
    UIBarButtonItem *map_bar=[[UIBarButtonItem alloc]initWithCustomView:btn_map];

    self.navigationItem.rightBarButtonItems=[[NSArray alloc]initWithObjects:list_bar,map_bar, nil];

尝试过的代码问题:两个按钮之间有空格。

我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

只需使用分段控制:您有一个完整的示例HERE

答案 1 :(得分:1)

使用自定义视图声明段控件

UISegmentedControl *control = (UISegmentedControl *) [segmentBarButton customView];

然后将其添加到barbuttonitem视图

UIBarButtonItem *segmentBarButton=[[UIBarButtonItem alloc] initWithCustomView:control];

不要忘记编写与分段控制自定义视图相关的行,例如您要求将红色或黑色图像添加到0或1段。