UIBarButton不可见

时间:2018-04-18 12:21:53

标签: ios objective-c user-interface

我正在学习Objective-C,我正在尝试以编程方式添加UIBarButtonItem。我在viewDidLoad

中这样做
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(addGuest)];

我有一个按下时调用的函数。

- (void)addGuest{

}

但是在导航栏中看不到条形按钮。

2 个答案:

答案 0 :(得分:1)

我有很棒的解决方案你可以使用它,只需在viewDidLoad或viewWillAppear中调用此方法

- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];

   [self DoneBtn];

 }
 //BarButton With Image no titleText on right handside

-(void)DoneBtn{

for (UIButton*obj in [self.navigationController.navigationBar subviews]) {

    if(obj.tag==1008){

        [obj removeFromSuperview];
    }
}
UIButton *Notification  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 , 35)];
[Notification setImage:[UIImage imageNamed:@"BellIcon"] forState:UIControlStateNormal];
[Notification addTarget:self action:@selector(NotificationBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:Notification];
[self.navigationItem setRightBarButtonItem:rightBarButtonItem];

rightBarButtonItem=nil;

//BarButton With Image no titleText on left handside

UIButton *Profile  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 , 35)];
[Profile setImage:[UIImage imageNamed:@"ProfileIcon"] forState:UIControlStateNormal];
[Profile addTarget:self action:@selector(ProfileBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *LeftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:Profile];
[self.navigationItem setLeftBarButtonItem:LeftBarButtonItem];

LeftBarButtonItem=nil;

}

//BarButton With titleText no image

UIButton *Notification  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100 , 35)];

NSString*titleName=[NSString stringWithFormat:@"Notification"];
[Notification setTitle:titleName forState:UIControlStateNormal];
[Notification setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[Notification addTarget:self action:@selector(NotificationBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:Notification];
[self.navigationItem setRightBarButtonItem:rightBarButtonItem];

rightBarButtonItem=nil;

答案 1 :(得分:0)

你应该在viewDidLoad

中这样做
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"Add" 
                             style:UIBarButtonItemStylePlain 
                            target:self 
                            action:@selector(addGuest:)];
[self.navigationItem setRightBarButtonItem:item animated:YES];