Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 658
mac10688 Avatar asked Sep 27 '22 23:09

mac10688


1 Answers

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");
        }
    }
}
like image 180
Iain Smith Avatar answered Dec 01 '22 07:12

Iain Smith