Xamarin iOS UIButton How To Click button programmatically?
Asked Answered
A

2

8

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);
}
Avocet answered 13/1, 2016 at 7:22 Comment(0)
M
5

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

myButton.SendActionForControlEvents (UIControlEvent.TouchUpInside);
Moriahmoriarty answered 13/1, 2016 at 10:6 Comment(3)
But wouldn't adding it to ViewDidLoad() mean the button would only be clicked the first time the View is loaded? What about when someone wants to go back to that View to use it again?Avocet
Use the same in ViewWillAppear but first of all check if the button is not null, if it is not this means that the user went back to that view.Moriahmoriarty
I tried using it from other methods also it works .. not necessary it has to be called from ViewDidLoad but it has to be called from main threadSpelaean
L
2

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
    }
}
Lebaron answered 30/7, 2018 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.