How to add an action to share button in navigation bar with Xcode

10,905

Solution 1

in your implementation.m file

- (void) viewWillAppear 
{
    [super viewWillAppear:animated];
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                    target:self
                                    action:@selector(shareAction:)];
    self.navigationItem.rightBarButtonItem = shareButton;
}

-(void)shareAction:(id)sender
{
    NSLog(@"share action");
}

Solution 2

Swift

    let shareBar: UIBarButtonItem = UIBarButtonItem.init(barButtonSystemItem:.Action, target: self, action: Selector("userDidTapShare"))

    self.navigationItem.rightBarButtonItem = shareBar

     func userDidTapShare() {
          //Implementation goes here ...
    }
Share:
10,905
Moussa
Author by

Moussa

Updated on July 28, 2022

Comments

  • Moussa
    Moussa almost 2 years

    I am trying to add an action to my share button in navigation bar but I don't know how and where to define my "shareAction" method. To add share button, I have the following code in viewWillAppear :

    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc]
                                    initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                    target:self
                                    action:@selector(shareAction:)];
    self.navigationItem.rightBarButtonItem = shareButton;
    
  • Our Man in Bananas
    Our Man in Bananas almost 10 years
    please elaborate on your answer, maybe explain what the code is doing and how it solves the problem. This will help others who see your code in the future