以编程方式添加两个带有图像的UIBarButtomItems

时间:2014-01-31 18:49:12

标签: ios uinavigationbar uibarbuttonitem

我正在尝试在viewDidLoad方法中使用以下代码将两个UIBarButtonItem添加到导航栏的左侧,但只显示第二个按钮:

//nav bar buttons


UIView* leftButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];

UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
leftButton.backgroundColor = [UIColor clearColor];
leftButton.frame = leftButtonView.frame;
[leftButton setImage:[UIImage imageNamed:@"toTop"] forState:UIControlStateNormal];
[leftButton setTitle:@"" forState:UIControlStateNormal];
leftButton.tintColor = [UIColor redColor]; //Your desired color.
leftButton.autoresizesSubviews = YES;
leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
[leftButton addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];


UIView* leftButtonView2 = [[UIView alloc]initWithFrame:CGRectMake(85, 0, 40, 40)];
UIButton* leftButton2 = [UIButton buttonWithType:UIButtonTypeSystem];
leftButton2.backgroundColor = [UIColor clearColor];
leftButton2.frame = leftButtonView.frame;
[leftButton2 setImage:[UIImage imageNamed:@"toSectionTop"] forState:UIControlStateNormal];
[leftButton2 setTitle:@"" forState:UIControlStateNormal];
leftButton2.tintColor = [UIColor redColor]; //Your desired color.
leftButton2.autoresizesSubviews = YES;
leftButton2.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
[leftButton2 addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];



[leftButtonView addSubview:leftButton];
[leftButtonView2 addSubview:leftButton2];

UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftButtonView];
UIBarButtonItem* leftBarButton2 = [[UIBarButtonItem alloc]initWithCustomView:leftButtonView2];
self.navigationItem.leftBarButtonItem = leftBarButton;
self.navigationItem.leftBarButtonItem = leftBarButton2;

欢迎任何帮助。谢谢

1 个答案:

答案 0 :(得分:0)

您要设置两次相同的属性,以便第二个设置替换第一个。尝试:

self.navigationItem.leftBarButtonItems = @[ leftBarButton, leftBarButton2 ];

请注意,这是设置leftBarButtonItem * s *,它采用一系列条形按钮。

此外,您不应该需要容器视图,它们不会添加任何值。按钮是视图,因此您可以直接使用它们。设置视图的帧原点也可能会导致问题。