2012-03-02 2 views
3

Я пытаюсь добавить пользовательскую метку на панели инструментов UINavigationController. Я следовал верхнему ответу за этот question, но он, похоже, не работает для меня, и я не знаю почему. Пользовательский текст не отображается, но кнопка есть. Он выделяется, когда я нажимаю на него, но у него нет текста.Добавление пользовательской метки в панель инструментов не работает

Вот мой код:

- (void) editToolbar{ 
    NSArray *toolbarItemsCopy = [self.toolbarItems copy]; 

    //set up the label 
    self.notificationsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width/0.25, 21.0f)]; 
    self.notificationsLabel.font = [UIFont fontWithName:@"Helvetica" size:20]; 
    self.notificationsLabel.backgroundColor = [UIColor clearColor]; 
    //self.notificationsLabel.textColor = [UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]; 
    self.notificationsLabel.textColor = [UIColor blueColor]; 
    self.notificationsLabel.text = @"Checking server"; 
    self.notificationsLabel.textAlignment = UITextAlignmentCenter; 

    //init a button with custom view using the label 
    UIBarButtonItem *notif = [[UIBarButtonItem alloc] initWithCustomView:self.notificationsLabel]; 

    //add to the toolbarItems 
    NSMutableArray *toolbarItemsMutableArray = [[NSMutableArray alloc]init]; 

    NSLog(@"toolbar %i", self.toolbarItems.count); 

    //have to add the custom bar button item in a certain place in the toolbar, it should be the 3rd item 
    for (int i = 0; i < toolbarItemsCopy.count; i++) { 
     if (i == 2){     
      [toolbarItemsMutableArray addObject:notif]; 
     } 
     NSLog(@"toolbar item %i %@", i,[toolbarItemsCopy objectAtIndex:i]); 
     [toolbarItemsMutableArray addObject:[toolbarItemsCopy objectAtIndex:i]]; 
    } 
    if (toolbarItemsCopy.count == 4){ 
    }else{ 
     //remove the previous custom label 
     [toolbarItemsMutableArray removeObjectAtIndex:3]; 
    } 
    self.toolbarItems = toolbarItemsMutableArray; 
    //[self.navigationController.toolbar setItems: toolbarItemsMutableArray animated:YES]; 

    NSLog(@"toolbar %i", self.toolbarItems.count); 
}https://stackoverflow.com/questions/ask 

Это то, что NSLog печатает:

Catalogue[361:10403] toolbar 4 
Catalogue[361:10403] toolbar item 0 <UIBarButtonItem: 0x8a24650> 
Catalogue[361:10403] toolbar item 1 <UIBarButtonItem: 0x8a36cd0> 
Catalogue[361:10403] toolbar item 2 <UIBarButtonItem: 0x8a36d30> 
Catalogue[361:10403] toolbar item 3 <UIBarButtonItem: 0x8a382f0> 
Catalogue[361:10403] toolbar 5 

Это, как я ее решил:

я должен Alloc и INIT в UILabel внутри вместо использования ivar.

UILabel *notificationsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)]; 
    notificationsLabel.font = [UIFont fontWithName:@"Helvetica" size:16]; 
    notificationsLabel.backgroundColor = [UIColor clearColor]; 
    //self.notificationsLabel.textColor = [UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]; 
    notificationsLabel.textColor = [UIColor whiteColor]; 
    notificationsLabel.text = @"Checking server"; 
    notificationsLabel.textAlignment = UITextAlignmentCenter; 
+0

Печатаются ли NSLog? – wizH

+0

@wizH да они. И я могу нажать на кнопку, просто нет текста. :) – acecapades

ответ

3

Я уверен, что этот код вам поможет. Внесите изменения в код, сохраняя при этом этот код. Я работал над этим и работает нормально,

UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; 
[self.view addSubview:toolBar]; 

UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f,  self.view.frame.size.width, 21.0f)]; 
[titleLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]]; 
[titleLbl setBackgroundColor:[UIColor clearColor]]; 
[titleLbl setTextColor=[UIColor blueColor]; 
[titleLbl setText:@"Title"]; 
[titleLbl setTextAlignment:UITextAlignmentCenter]; 

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:titleLbl]; 
NSArray *toolbarItemArr = [NSArray arrayWithObjects:button, nil]; 
[toolBar setItems:toolbarItemArr animated:YES]; 

Для лучшего понимания вы можете по следующим ссылкам: UIToolBar Class Reference и UIBarButtonItem Class Reference

+0

Конечно. Я попробую это, и я дам вам знать. Дело в том, что я просто хочу редактировать существующие элементы панели инструментов, а не alloc-init, а затем добавлять туда. Но я попробую. – acecapades

+0

Привет @acecapades определенно это будет работать, потому что вы пытаетесь удалить объект из массива элементов панели инструментов и назначить новый объект, чтобы все логики были такими же. Но вы должны тщательно реализовать этот код в своем коде. Надеюсь, ты сможешь найти свой ответ. удачи !! –

+0

Привет @acecapades Я думаю, что вы получили свой ответ, спасибо за принятие моего ответа. !! –

2

Я знаю, что этот вопрос ответил и старый, но у меня был такой же опыт , и нашел что-то интересное. Мой код должен отображать (на панели инструментов) кнопку иногда, а ярлык - некоторые другие, в зависимости от состояния программы. Если я создаю объект UILabel в моем классе контроллера, и использовать его в вызовах

UIBarButtonItem *myItem = [[UIBarButtonItem alloc] initWithCustomView: _myUILabel]; 
[self setToolbarItems: [NSArray arrayWithObject: myItem]]; 
[myItem release]; 

каждый раз, когда мне нужно, чтобы перейти от кнопки на этикетке, то метка не будет отображаться (На самом деле он показывает вверх по в первый раз, а после переключения назад и вперед один раз, он перестает показывать). Я потратил несколько часов на этот вопрос, и если это не тот факт, что я лысый, я бы, наверное, вытащил все мои волосы в отчаянии. Я подтвердил, что все мои счета остаются в порядке. Моя сохраненная метка хороша и действительна.

Я обнаружил, что если я создаю новый ярлык каждый раз, когда мне нужно показать его на панели инструментов, проблема исчезнет. Существует определенная проблема в обработке UILabel внутри setToolbarItems. Итак, совет, создайте новый ярлык, установите текст и т. Д., Оберните его в UIToolBarItem и снова настройте элементы панели инструментов.

Это не идеальный вариант, он выполняет выделение и освобождает больше, но он работает. Надеюсь, это поможет кому-то там.

Смежные вопросы