Добавление пользовательской метки на панели инструментов не работает - PullRequest
3 голосов
/ 02 марта 2012

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

Вот мой код:

- (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

Я решил это:

Я должен выделить и инициализировать UILabel внутри функции вместо использования ивара.

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;

Ответы [ 2 ]

3 голосов
/ 02 марта 2012

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

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 и Ссылка на класс UIBarButtonItem

2 голосов
/ 05 мая 2012

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

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

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

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...