customView на левой кнопке UINavigationBar - PullRequest
1 голос
/ 28 февраля 2010

Я пытаюсь реализовать UINavigationBar с пользовательскими элементами управления. Итак, я добавил UIView в левой части UINavigationBar и пытаюсь добавить элементы управления в этот UIView с помощью следующего кода:

UIView *view = navigationController.navigationItem.leftBarButtonItem.customView;
UIButton *button = [[UIButton alloc] initWithFrame:view.frame];
[button setTitle:@"TEST" forState:UIControlStateNormal];
[view addSubview:button];
[button sizeToFit];
[button release];

Код работает, но кнопка не появляется.

Любая помощь будет оценена. Спасибо.

UPD

ОК, я попробовал код ниже и сделал такую ​​вещь:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
[button setTitle:@"XXX" forState:UIControlStateNormal];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
navigationController.visibleViewController.navigationItem.leftBarButtonItem = customItem;
[customItem release];
[button release];

Заголовок "XXX" появился, но выглядит как простой ярлык, а не кнопка. Есть идеи?

Ответы [ 2 ]

4 голосов
/ 05 марта 2010

Да, ваша UIButton не имеет затенения. Я использовал UISegmentedControl, чтобы получить затенение бесплатно:

// Add the Menu button to the navigation bar
NSString* menuLabel = "ShadeButton";
CGSize textSize = [menuLabel sizeWithFont:[UIFont systemFontOfSize:15.0]];
UISegmentedControl* menuSegmentedButton = [[UISegmentedControl alloc]
    initWithFrame:CGRectMake(0.0f, 0.0f, textSize.width, 29.0f)];
menuSegmentedButton.momentary = YES;
menuSegmentedButton.selected = NO;
menuSegmentedButton.segmentedControlStyle = UISegmentedControlStyleBar;
[menuSegmentedButton insertSegmentWithTitle:menuLabel atIndex:0
                              animated:NO];
[menuSegmentedButton addTarget:self action:@selector(doMenu)
         forControlEvents:UIControlEventValueChanged];
UIBarButtonItem* barButton = [[UIBarButtonItem alloc] 
    initWithCustomView:menuSegmentedButton];
[menuSegmentedButton release];
self.navigationItem.rightBarButtonItem = barButton;

Создайте свой UIBarButtonItem с помощью UISegmentedControl, как показано выше, а не UIButton, и вы должны получить эффект, который вам нужен. Альтернатива состоит в том, чтобы больше работать с кнопкой и самостоятельно создать для нее текстуру / собственное изображение.

3 голосов
/ 28 февраля 2010

Примечание совершенно верно.

Если вы просто хотите другой заголовок:

UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithTitle:@"TEST" style:UIBarButtonItemStylePlain target:nil action:nil];
navigationController.navigationItem.leftBarButtonItem = customItem;
[customItem release];

Если вы действительно хотите пользовательский вид:

// Create Custom View called myView.
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:myView];
navigationController.navigationItem.leftBarButtonItem = customItem;
[customItem release];
...