简体   繁体   English

Xamarin iOS UIButton如何以编程方式单击按钮?

[英]Xamarin iOS UIButton How To Click button programmatically?

I'm attempting to fake the act of clicking a button, by programmatically calling it within my ViewWillAppear() function. 我试图通过在ViewWillAppear()函数中以编程方式调用按钮来伪造单击按钮的行为。

The onclick function is defined in my ViewDidLoad(), and you can see I am trying to use a Perform Selector to manually call the button. onclick函数是在我的ViewDidLoad()中定义的,您可以看到我正在尝试使用“执行选择器”来手动调用按钮。

The button does not appear to be running. 该按钮似乎没有在运行。 Any ideas? 有任何想法吗?

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

    idButtonScanLoad.TouchUpInside += async (sender, ea) =>
    {
        System.Console.WriteLine("Scan button pressed");
    };

}

[Export("TouchUpInsideEvent:")]
private void TouchUpInsideEvent(NSObject sender)
{
    Console.WriteLine("yay!");
}

public override void ViewWillAppear(bool animated)
{
    base.ViewWillAppear(animated);

    this.PerformSelector(new ObjCRuntime.Selector("TouchUpInsideEvent:"), this as NSObject, 10f);
}

这是答案,您应该从ViewDidLoad方法调用它。

myButton.SendActionForControlEvents (UIControlEvent.TouchUpInside);

If you want to create a button's click event, you can use the this 如果要创建按钮的click事件,可以使用this

public override void ViewDidLoad()
{
     Mybutton.AddTarget(ButtonEventHandler, UIControlEvent.TouchUpInside);
}

public void ButtonEventHandler(object sender, EventArgs e)
{
    if(sender==Mybutton)
    {
       //do stuff here
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM