gpt4 book ai didi

ios - MVVM 模式和 Storyboard iOS

转载 作者:可可西里 更新时间:2023-11-01 03:46:03 24 4
gpt4 key购买 nike

当项目包含 Storyboard 时,有人可以向我解释如何实现 MVVM 模式吗?

在许多示例中,我看到我必须使用 .xib 文件。和 init ViewControllers 像这样:

-(instancetype)initWithModelView:(ViewModel *)viewModel{

self = [super init];

if(self){

_viewModel = viewModel;
}

return self;
}

但是对于 Storyboard ,我不能init viewControllers, Storyboard 会为我做这件事。我应该改用属性吗?

UINavigationController *nav = (UINavigationController *)[self.viewControllers objectAtIndex:0];
HomeViewController *hvc = (HomeViewController *)[nav.viewControllers objectAtIndex:0];
hvc.viewModel = viewModel;

self 是 UITabBarController

最佳答案

您可以在 UIViewControllerprepareForSegue:sender: 方法中初始化一个 viewModel 属性

这是一个很棒的示例 MVVM 应用程序的链接 C-41 by Ash Furrow

该应用程序中的 viewModel 初始化示例:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

ASHDetailViewController *viewController = segue.destinationViewController;
viewController.viewModel = [self.viewModel detailViewModelForIndexPath:indexPath];
} else if ([[segue identifier] isEqualToString:@"editRecipe"]) {
ASHEditRecipeViewController *viewController = (ASHEditRecipeViewController *)[segue.destinationViewController topViewController];
viewController.viewModel = [self.viewModel editViewModelForNewRecipe];
}
}

关于ios - MVVM 模式和 Storyboard iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25282575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com