Skip to content

AA 1.15. Adding Buttons to Navigation Bars Using UIBarButtonItem

rayastar edited this page Feb 7, 2015 · 1 revision

Let’s then have a look at an example where we add a button to the right side of our navigation bar. In this button, we will display the text “Add”:

-(void)viewDidLoad
{
    [super viewDidLoad];
    //1.12
    self.title = @"First Controller";
    self.displaySecondViewController = [UIButton
                                        buttonWithType:UIButtonTypeSystem];
    [self.displaySecondViewController
     setTitle:@"Display Second View Controller"
     forState:UIControlStateNormal];
    [self.displaySecondViewController sizeToFit];
    self.displaySecondViewController.center = self.view.center;
    [self.displaySecondViewController
     addTarget:self action:@selector(performDisplaySecondViewController:)    forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.displaySecondViewController];


    //1.15
    // добавление кнопки-надпись
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithTitle:@"Add"
                                     style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(performAdd:)];

    //Системная кнопка +
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc]
     initWithBarButtonSystemItem:UIBarButtonSystemItemDone
     target:self
     action:@selector(performAdd:)];

    //cwitch
    UISwitch *simpleSwitch = [[UISwitch alloc] init];
    simpleSwitch.on = YES;
    [simpleSwitch addTarget:self
                     action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithCustomView:simpleSwitch];


    //стрелки
    NSArray *items = @[
                       @"Up",
                       @"Down"
                       ];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]
                                            initWithItems:items];
    segmentedControl.momentary = YES;
    [segmentedControl addTarget:self
                         action:@selector(segmentedControlTapped:)
               forControlEvents:UIControlEventValueChanged];
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
}

-(void) segmentedControlTapped:(UISegmentedControl *)paramSender
{
    switch (paramSender.selectedSegmentIndex)
    { case 0:
        {
            NSLog(@"Up");
            break;
        }
        case 1:{
            NSLog(@"Down");
            break;
        }
    }
}

-(void)performAdd:(id)paramSender
{
    NSLog(@"Action method got called.");
}

-(void)switchIsChanged:(id)paramSender
{
    NSLog(@"Action method switch got called.");
}

//
Clone this wiki locally