barinelg
barinelg

Reputation: 23

Clicked event for UIBarButtonItem appears to not work in MonoTouch

I'm trying to create a custom back button, and everything seems to work except the Clicked event.

I have 2 screens that I am going between. We will call them Screen1 and Screen2. There is a button in Screen1 that takes me to Screen2 when clicked.

The following code is how I'm attempting to create a custom back, which has been placed in both ViewDidLoad and ViewWillDisappear of Screen1 (the following is what I have in ViewWillDisappear). The code used in both functions are the last two lines in the following code.

protected override void ViewWillDisappear(bool animated) {
    base.ViewWillDisappear(animated);
    this.NavigationController.SetNavigationBarHidden(false, animated);
    UIBarButtonItem backBtn = new UIBarButtonItem("NewTitle", UIBarButtonItemStyle.Plain, delegate { Console.WriteLine("clicked"); });
    this.NavigationItem.BackBarButtonItem = backBtn;
}

When running, the word "clicked" never appears in the console when I click the back button in Screen2. I've also tried hiding the default by calling

this.NavigationItem.SetHidesBackButton(true, false);

before creating the button, but it didn't affect anything.

Any advice will be greatly appreciated!

Upvotes: 1

Views: 3271

Answers (2)

barinelg
barinelg

Reputation: 23

After much research and trial and error, I came across the following post: http://adrianhosey.blogspot.com/2009/06/why-wont-my-backbarbuttonitem-use-its.html (note that there is some foul language in the post). It appears that setting the variable BackBarButtonItem to a custom button will not work; you can change the text, but that appears to be it.

However, another post here says that it can work in the pushing controller, though it never seemed to work for me: Button Questions in MonoTouch.

To fix this issue, the following code worked for me:

public override void ViewDidLoad() {
    base.ViewDidLoad();
    this.NavigationItem.SetHidesBackButton(true, false);
    UIBarButtonItem backBtn = new UIBarButtonItem("Back", UIBarButtonItemStyle.Plain, delegate {
        Console.WriteLine("clicked");
        //one of the NavigationController pop functions to go back
    });
    this.NavigationItem.LeftBarButtonItem = backBtn;
}

Upvotes: 1

poupou
poupou

Reputation: 43553

Sometimes the default .ctor do not work as we expect. IOW it call the init selector but that does not always provide a fully initialized instance (most of the time an ObjectiveC exception is raised).

To be sure try using the following code:

UIBarButtonItem backBtn = new UIBarButtonItem ("NewTitle", UIBarButtonItemStyle.Plain, delegate {
   Console.WriteLine("clicked");
});
this.NavigationItem.BackBarButtonItem = backBtn;

If that works then please fill a bug report to http://bugzilla.xamarin.com/ and add a link back to this question.

Upvotes: 1

Related Questions