Ios 如何将自定义项添加到导航栏
我已经用不同类型的代码为我的导航栏添加自定义项奋斗了几个小时。不幸的是,它失败了,并且没有调试错误。现在我只能更改酒吧的标题 代码添加到特定ViewController的viewDidLoad方法中:Ios 如何将自定义项添加到导航栏,ios,cocoa-touch,uibarbuttonitem,Ios,Cocoa Touch,Uibarbuttonitem,我已经用不同类型的代码为我的导航栏添加自定义项奋斗了几个小时。不幸的是,它失败了,并且没有调试错误。现在我只能更改酒吧的标题 代码添加到特定ViewController的viewDidLoad方法中: UIBarButtonItem *gotoNext = [[UIBarButtonItem alloc] initWithTitle:@"Goto next" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNext
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;
我能看到的代码唯一的错误是选择器名称末尾缺少冒号。应改为:
UIBarButtonItem *gotoNext = [[UIBarButtonItem alloc] initWithTitle:@"Goto next" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextAction:)];
为此,您必须在导航栏项中添加自定义视图
UIBarButtonItem *bi = [[UIBarButtonItem alloc]
initWithCustomView:myButton];
有关更多详细信息,请参阅下面的链接
您可以为uibarbuttonite编写一个类别
+ (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];
}
若你们看我的原始帖子,我用我测试过的代码更新了它,不幸的是它并没有工作。容器的框架设置在哪里?背景色?