如何将自定义项添加到导航栏

时间:2012-05-10 23:23:50

标签: ios cocoa-touch uibarbuttonitem

我使用不同类型的代码进行了几个小时的战斗,以向我的导航栏添加自定义项目。不幸的是它失败了,并且没有调试错误。现在我只能更改栏的标题。

代码添加在特定ViewController中的viewDidLoad方法中:

UIBarButtonItem *gotoNext = [[UIBarButtonItem alloc] initWithTitle:@"Goto next" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextAction)];

self.navigationItem.rightBarButtonItem = gotoNext;

我尝试了以下代码,但遗憾的是没有运气:

UIView* container = [[UIView alloc] init];
UIButton * button = [[UIButton alloc] init];

[button setTitle:@"Test" forState:UIControlStateNormal];

[container addSubview:button];

UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:container];

self.navigationItem.rightBarButtonItem = item;

3 个答案:

答案 0 :(得分:1)

我唯一看错的代码就是选择器名称末尾缺少冒号。它应该是:

UIBarButtonItem *gotoNext = [[UIBarButtonItem alloc] initWithTitle:@"Goto next" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextAction:)];

答案 1 :(得分:0)

为此,您必须在导航栏项目

中添加自定义视图
UIBarButtonItem *bi = [[UIBarButtonItem alloc]
                       initWithCustomView:myButton];

有关详细信息,请参阅以下链接

Adding bar button item in navigation bar

How to add several UIBarButtonItems to a NavigationBar?

答案 2 :(得分:0)

您可以为UIBarButtonItem编写一个类别。

+ (instancetype)itemWithImage:(UIImage *)buttonImage
              buttonTitle:(NSString *)title
              buttonFrame:(CGRect)frame
                   target:(id)target
                   action:(SEL)action{
    UIButton *button = [[UIButton alloc]initWithFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setImage:buttonImage forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    return [[UIBarButtonItem alloc]initWithCustomView:button];
  }