Ставим 4 кнопки панели навигации

Я новичок в программировании iOS, и мне интересно, можно ли поместить 4 кнопки панели в UINavigationBar? Я пробовал несколько методов, которые я нашел при переполнении стека, но позиции buttons не равны.

Вот пример скриншота

введите здесь описание изображения.

Метод, который я использовал для кодирования своей панели навигации:

UIToolBar *tools = [[UIToolBar alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
UIImage *backImage = [UIImage imagedName:@"backIcon.png"];
UIImage *shareImage = [UIImage imagedName:@"shareIcon.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:backImage forState:UIControlStateNormal];

// create the button and assign the image to the leftsidebutton
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:backImage forState:UIControlStateNormal];
backButton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);

[backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];

UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
[shareButton setImage:shareImage forState:UIControlStateNormal];
shareButton.frame = CGRectMake(0, 0, shareImage.size.width, shareImage.size.height);

//create space between the buttons
UIBarButtonItem *bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];

UIBarButtonItem *customBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
UIBarButtonItem *shareBarButton = [[UIBarButtonItem alloc] initWithCustomView:shareButton];
self.navigationItem.hidesBackButton = YES;
NSArray *leftActionButtonItems = @[customBarButton, bi, shareBarButton];
[tools setItems:leftActionButtonItems animated:NO];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];

Я сделал то же самое для rightBarButtonItem, но это не так хорошо работает.

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


person user2909432    schedule 29.10.2013    source источник


Ответы (4)


Попробуй это :

Редактировать: отображается правильно, проверьте:

введите здесь описание изображения

взять файл .h:

  UIToolbar *toolBar_T;
  UIBarButtonItem *item1,*item2,*item3,*item4;

взять .m файл:

toolBar_T=[[UIToolbar alloc] init];
toolBar_T.frame=CGRectMake(0,5,168, 44);
[self.view addSubview:toolBar_T];

UIButton *button0 = [UIButton buttonWithType:UIButtonTypeCustom];
[button0 setImage:[UIImage imageNamed:@"1.png"]  forState:UIControlStateNormal];
[button0 addTarget:self action:@selector(button0:) forControlEvents:UIControlEventTouchUpInside];
button0.frame = CGRectMake(0, 7, 35,29);
item1 = [[UIBarButtonItem alloc] initWithCustomView:button0];

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(button1:) forControlEvents:UIControlEventTouchUpInside];
button1.frame = CGRectMake(0, 7, 35,29));
item2 = [[UIBarButtonItem alloc] initWithCustomView:button1];


UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:@"3.png"] forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(button2:) forControlEvents:UIControlEventTouchUpInside];
button2.frame = CGRectMake(0, 7, 35,29);
item3 = [[UIBarButtonItem alloc] initWithCustomView:button2];

 UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setImage:[UIImage imageNamed:@"4.png"] forState:UIControlStateNormal];

[button3 addTarget:self action:@selector(button3:) forControlEvents:UIControlEventTouchUpInside];
button3.frame = CGRectMake(0, 7, 35,29);
item4 = [[UIBarButtonItem alloc] initWithCustomView:butto3];

NSArray *buttons = [NSArray arrayWithObjects: item1, item2,item3, nil];

[toolBar_T setItems: buttons animated:NO];
toolBar_T.barStyle=-1;// For Clear backgroud
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolBar_T];

Надеюсь, это поможет.

Удачного кодирования...

person Dhaval Bhadania    schedule 29.10.2013
comment
привет, Дхавал, твой код работает, но кнопки расположены слишком близко друг к другу... можно ли как-то расставить кнопки? - person user2909432; 29.10.2013
comment
@user2909432 user2909432 проверьте мой ответ на редактирование и установите CGRectMake для кнопок, панели инструментов, что вам нужно. - person Dhaval Bhadania; 29.10.2013

Вы можете попробовать что-то вроде этого...

-(void)setupToolbarButtons:(UIViewController *)navC
    {

        //create a toolbar in the right

        UIToolbar *tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 135, 44.01)];
        tools.delegate = self;
        tools.barTintColor = [UIColor clearColor];


        //create the array to hold the buttons, which then gets added to the toolbar
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:4];

        //create a standart 'play' button
        UIBarButtonItem *bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:nil];
        [buttons addObject:bi];
        [bi release];

        //create a standart 'stop' button
        bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:nil];
        [buttons addObject:bi];
        [bi release];

        //create a standart 'fast forward' button
        bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:self action:nil];
        [buttons addObject:bi];
        [bi release];

        //create a standart 'pause' button
        bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:nil];
        [buttons addObject:bi];
        [bi release];

        //stick the buttons in the toolbar
        [tools setItems:buttons animated:NO];
        [buttons release];

        //and put the toolbar in the nav bar
        navC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
        [tools release];

    }

...также вы можете добавить разделитель, если это необходимо

bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[buttons addObject:bi];
[bi release];

а если что-то не так в вертикальном интервале, то добавить вот это

- (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar
{
    return UIBarPositionTopAttached;
}
person Konstantin    schedule 29.10.2013

UINavigationBar Наследует UIView, поэтому вы можете просто добавить любой объект.

person Mutawe    schedule 29.10.2013
comment
Это означает, что вместо того, чтобы помещать его в панель навигации, я помещаю изображения в UIView? - person user2909432; 29.10.2013

Попробуйте следующий код

self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:customBarButton, bi, shareBarButton, nil];

self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:BUTTON OBJECTS, nil];
person Vaisakh    schedule 29.10.2013
comment
Привет, vaisakh, есть предупреждение, когда я опробовал этот метод, несовместимые типы указателей, назначенные «UIBarButtonItem *» из «NSArray *» - person user2909432; 29.10.2013
comment
у меня это работает... в любом случае попробуйте эту ссылку stackoverflow.com/questions/2413126/ - person Vaisakh; 29.10.2013