In Xamarin iOS designer, how can I prevent code from running in ViewDidLoad?

In the iOS Xamarin Storyboard Designer, the ViewDidLoad ViewController code is generated and run automatically by simply looking at the storyboard. This is great for programmatic design elements because I can see them in the designer view without having to run the simulator, but I also need to make an API call from the ViewDidLoad and this will cause the constructor to fail with an error . Custom components are not because problems have been discovered . "

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

    AddWhiteGradient();
    AddGreenGradient();

    await CallApi();
}

      

In this example, I like the designer calling the AddWhiteGradient () and AddGreenGradient () functions because I can see the result of this in the storyboard, but I am waiting for CallApi () to fail the constructor.

Is there a programmatic check to see if I'm in the designer's view or not?

Something like:

if (!IsInDesignerView) {
    await CallApi();
}

      

or

#if !DESIGNER
await CallApi();
#endif

      

+2


source to share


1 answer


I created a hack that works, so I will not mark this as an answer because this is not the way Xamarin has provided or will provide, but it does the job for now.

The Studio Storyboard designer does not raise AppDelegate events, so you can use that to create a validation.

AppDelegate.cs



public partial class AppDelegate: UIApplicationDelegate
{
    public static bool IsInDesignerView = true;

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        IsInDesignerView = false;

        return true;
    }
}

      

ViewController

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

    if (!AppDelegate.IsInDesignerView)
    {
        await CallApi();
    }
}

      

+1


source







All Articles