如何在xamarin ios C#中以编程方式启动UIButton的TouchUpInside

本文关键字:方式 编程 启动 UIButton TouchUpInside xamarin ios | 更新日期: 2023-09-27 18:30:03

我正试图以编程方式激发Uibutton的touchupinside事件。我该怎么做?我尝试的代码使用PerformSelector,但我得到了这个错误

"Error MT4117: The registrar found a signature mismatch in the method
 'VCPAckage2.ActivityViewController.TouchUpInsideEvent' - the
 selector 'TouchUpInsideEvent:' indicates the method takes 1
 parameters, while the managed method has 2 parameters. "

我想实现类似的目标

UIButton.FireEvent("TouchUpInsideEvent") - this will fire the TouchUpInsideEvent
UIButton.PerformSelector(new MonoTouch.ObjCRuntime.Selector ("TouchUpInsideEvent:"), null, 2000f);

这是代码

 private void LoadFn()
 {
    UIButton btnSubmit = new UIButton(new RectangleF(0,0,View.Frame.Width,40));
    btnSubmit.TouchUpInside+=TouchUpInsideEvent;
 }   
 [Export("TouchUpInsideEvent:")]
 private void TouchUpInsideEvent(object sender,EventArgs e){
 float yy = AppConstants.ZeroVal;
 if (FeedbackSubmittedReturnFlag == true) {
        yy =  ChildScrollView2.Subviews[1].Frame.Height+ChildScrollView2.Subviews[1].Frame.Y;
 }
     this.ParentScrollView.SetContentOffset (new PointF (View.Frame.Width, yy), false);
 }

如何在xamarin ios C#中以编程方式启动UIButton的TouchUpInside

下面的代码片段就足够了

btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);

它必须从主线程调用

上面有一些不同的东西。

首先,MT4117是正确的。之所以会发生这种情况,是因为[Export]属性为只有一个参数的方法指定了一个选择器(即它只有一个:),而托管方法有两个参数(这是.NET事件的默认值)。登记员将发现此类情况并报告错误。

其次,PerformSelector方法是performSelector:...选择器上的绑定(大多数是在NSObject协议上定义的,而不是类)。因此,它们具有相同的限制(例如,它们可以处理的参数数量)。

第三,有几种方法可以调用自己的代码。一个简单的方法是,就像@jonathanpeppers建议的那样,在需要时直接调用您的托管方法。

另一种方法是调整代码以匹配12要求,例如

// assign one (two parameters) method as a .NET event
btnSubmit.TouchUpInside += TouchUpInsideEvent;
...
// call another (one parameter) method like a selector
any_nsobject.PerformSelector (new Selector ("TouchUpInsideEvent:"), sender as NSObject, 0f);
...
// have the 2 parameters method call the(1 parameter) export'ed method
private void TouchUpInsideEvent (object sender, EventArgs e)
{
    TouchUpInsideEvent (sender as NSObject);
}
[Export ("TouchUpInsideEvent:")]
private void TouchUpInsideEvent (NSObject sender)
{
    Console.WriteLine ("yay!");
}