在 Xamarin iOS 设计器中,如何防止代码在 ViewDidLoad 中运行? [英] In Xamarin iOS designer, how can I prevent code from being run in ViewDidLoad?

查看:12
本文介绍了在 Xamarin iOS 设计器中,如何防止代码在 ViewDidLoad 中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Xamarin iOS Storyboard 设计器中,ViewController 的 ViewDidLoad 代码会在查看情节提要时自动构建和运行.这对于程序化设计元素非常有用,因为我可以在设计器视图中看到它们而无需启动模拟器,但我还需要从 ViewDidLoad 进行 API 调用,这会使设计器崩溃并显示错误 自定义组件没有被由于检测到问题而呈现".

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

在这个例子中,我喜欢设计师调用 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?

类似于:

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

#if !DESIGNER
await CallApi();
#endif

推荐答案

我创建了一个有效的 hack,所以我不会将其标记为答案,因为它不是 Xamarin 已经提供或将提供的方式,但这确实暂时工作.

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.

Studio Storyboard 设计器不会调用 AppDelegate 事件,因此您可以利用它来创建检查.

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

视图控制器

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

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

这篇关于在 Xamarin iOS 设计器中,如何防止代码在 ViewDidLoad 中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆