Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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);
}
like image 692
Sami.C Avatar asked Jan 13 '16 07:01

Sami.C


2 Answers

Here is the answer, you should call it from your ViewDidLoad method.

myButton.SendActionForControlEvents (UIControlEvent.TouchUpInside);
like image 156
Shalva Avanashvili Avatar answered Oct 22 '22 16:10

Shalva Avanashvili


If you want to create a button's click event, you can use the this

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

public void ButtonEventHandler(object sender, EventArgs e)
{
    if(sender==Mybutton)
    {
       //do stuff here
    }
}
like image 1
Divyesh_08 Avatar answered Oct 22 '22 17:10

Divyesh_08