【问题标题】:Adding two UIBarButtomItems with image programmatically以编程方式添加两个带有图像的 UIBarButtomItem
【发布时间】:2014-01-31 18:49:11
【问题描述】:

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

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

欢迎任何帮助。谢谢

【问题讨论】:

    标签: ios uinavigationbar uibarbuttonitem


    【解决方案1】:

    您将同一属性设置了两次,因此第二个设置替换了第一个设置。试试:

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

    注意这是设置 leftBarButtonItem*s*,它接受一个条形按钮数组。

    另外,您不需要容器视图,它们没有任何价值。按钮是视图,因此您可以直接使用它们。设置视图的框架原点也可能会导致问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2019-06-25
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多