0

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

代码添加到特定 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;
4

3 回答 3

1

我唯一能看到您的代码有问题的是您的选择器名称末尾缺少冒号。它应该是:

UIBarButtonItem *gotoNext = [[UIBarButtonItem alloc] initWithTitle:@"Goto next" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextAction:)];
于 2012-05-11T01:50:03.930 回答
0

为此,您必须在导航栏项目中添加自定义视图

UIBarButtonItem *bi = [[UIBarButtonItem alloc]
                       initWithCustomView:myButton];

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

在导航栏中添加栏按钮项

如何将几个 UIBarButtonItems 添加到 NavigationBar?

于 2012-05-11T05:33:17.737 回答
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];
  }
于 2018-04-13T07:16:02.617 回答