mac10688
mac10688

Reputation: 2205

Click Handler Xamarin

I am trying to register a click event in my Xamarin.iOS application. I don't want to register the events in a method like this though.

http://developer.xamarin.com/recipes/ios/standard_controls/buttons/handle_clicks/

I want to register them from the storyboard and there seems to be functionality to do this.

Attempting to bind event to method in controller

and in my ViewController I have the following code:

    public void ButtonPressed(object sender, EventArgs ea)
    {
        UIAlertView error = new UIAlertView("Test Title", "This is a test", null, "Ok", null);
        error.Show();
    }

When I run the application and press the button, I get an error in the appDelegate

Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: -[HomeViewController ButtonPressed:]: unrecognized selector sent to instance 0x14691650

How can I register the click event?

Upvotes: 5

Views: 495

Answers (2)

Egor Samets
Egor Samets

Reputation: 109

Check the partial class for your ViewController. It should have something like this:

[Action ("ButtonPressed:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void ButtonPressed (UIButton sender);

Then put partial to your method:

public partial void ButtonPressed(object sender, EventArgs ea) {
    //...
}

Upvotes: 0

Iain Smith
Iain Smith

Reputation: 9703

Check your designer file for your ViewController it will have somethign like this:

using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace TEST
{
    [Register ("ViewController")]
    partial class ViewController
    {
        [Action ("ButtonPressed:")]
        [GeneratedCode ("iOS Designer", "1.0")]
        partial void ButtonPressed (UIButton sender);

        void ReleaseDesignerOutlets ()
        {
        }
    }
}

So just implement that method like so:

using System;
using UIKit;

namespace TEST
{
    public partial class ViewController : UIViewController
    {
        public ViewController (IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
        }

        partial void ButtonPressed (UIButton sender)
        {
            Console.Write ("HEY mark this answer as accepted");
        }
    }
}

Upvotes: 4

Related Questions