0

任何人都可以帮助我如何使用标题视图属性向导航标题视图添加两个按钮。我试过了,但只能使用以下代码添加一个按钮。

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;
4

2 回答 2

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;

输出:

输出示例图像

于 2013-09-28T07:30:13.247 回答
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];
于 2013-09-28T07:21:54.993 回答