单击处理程序Xamarin

时间:2015-08-20 20:46:40

标签: xamarin xamarin.ios

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

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

我想从故事板中注册它们,似乎有这样的功能。

Attempting to bind event to method in controller

在我的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异常。名称:   NSInvalidArgumentException原因: - [HomeViewController   ButtonPressed:]:无法识别的选择器发送到实例0x14691650

如何注册点击事件?

2 个答案:

答案 0 :(得分:3)

检查你的设计器文件中的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");
        }
    }
}

答案 1 :(得分:0)

检查您的ViewController的局部类。它应该是这样的:

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

然后将partial放入您的方法:

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