单击处理程序 Xamarin

Click Handler Xamarin

我正在尝试在我的 Xamarin.iOS 应用程序中注册一个点击事件。不过我不想用这样的方法注册事件。

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

我想从情节提要中注册它们,似乎有执行此操作的功能。

在我的 ViewController 中,我有以下代码:

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

当我 运行 应用程序并按下按钮时,我在 appDelegate

中收到错误消息

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

如何注册点击事件?

检查您的 ViewController 设计器文件,其中包含如下内容:

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 ()
        {
        }
    }
}

所以只需像这样实现该方法即可:

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");
        }
    }
}

检查您的 ViewController 的部分 class。它应该是这样的:

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

然后将 partial 放入您的方法中:

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