如何将两个按钮添加到导航栏标题视图

时间:2013-09-28 07:19:24

标签: iphone ios objective-c uinavigationcontroller

任何正文都可以帮助我使用标题视图属性将两个按钮添加到导航标题视图。我试过但是,只能使用以下代码添加一个按钮。

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
customView.backgroundColor = [UIColor redColor];

UIButton *b1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
UIButton *b2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

[b1 setTitle:@"Hai" forState:UIControlStateNormal];
[b2 setTitle:@"Hello" forState:UIControlStateNormal];

[customView insertSubview:b1 atIndex:0];
[customView insertSubview:b2 atIndex:1];   

self.navigationItem.titleView = customView;

2 个答案:

答案 0 :(得分:0)

这是因为您为两个按钮添加了相同的框架。因此,按钮实际上是重叠的。您应该使用此代码:

UIButton *b1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
UIButton *b2=[[UIButton alloc]initWithFrame:CGRectMake(60, 0, 50, 50)];

然后,您只需将这些按钮添加到自定义视图中即可。

[cusotmView addSubView:b1];
[cusotmView addSubView:b2];

错误原因:

您无法直接添加UIButtons。您需要先将它们包装为UIBarButtonItems

示例代码:

UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithCustomView:b1];
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithCustomView:b2];
[cusotmView addSubView:btn1];
[cusotmView addSubView:btn2];

答案 1 :(得分:0)

使用此代码:

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
customView.backgroundColor = [UIColor redColor];

UIButton *b1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
UIButton *b2 = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, 50, 50)];

[b1 setTitle:@"Hai" forState:UIControlStateNormal];
[b2 setTitle:@"Hello" forState:UIControlStateNormal];

[customView insertSubview:b1 atIndex:0];
[customView insertSubview:b2 atIndex:1];

self.navigationItem.titleView = customView;

输出:

Example image of output