问题
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