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

核能气质少年 提交于 2020-01-21 17:53:08

问题


In the Xamarin iOS Storyboard designer, the ViewDidLoad code of the ViewController gets built and run automatically when just looking at the storyboard. This is great for programmatic design elements because I can see them in designer view without having to start the simulator, but I also need to make an API call from ViewDidLoad and that crashes the designer with the error "Custom components are not being rendered because problems were detected".

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 that in the storyboard, but await CallApi() crashes the designer.

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

Something like either:

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

or

#if !DESIGNER
await CallApi();
#endif

回答1:


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

The Studio Storyboard designer does not call the AppDelegate events, so you can utilize that to create a check.

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();
    }
}


来源:https://stackoverflow.com/questions/25825424/in-xamarin-ios-designer-how-can-i-prevent-code-from-being-run-in-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!