gpt4 book ai didi

iOS:模态 viewController 如何记住它的属性?

转载 作者:行者123 更新时间:2023-11-28 21:58:48 25 4
gpt4 key购买 nike

问题:在我的应用程序中,我在 Storyboard 中使用模态转场展示了一个 UIViewController。该 viewController 有一个 UITableView,用户可以选择一个单元格。然后我关闭那个 viewController 并返回。我想要做的是当 Controller 再次出现时,选定的单元格会突出显示。所以我想将所选单元格的 indexPath 保存在一个属性中,并在 viewWillAppear 中设置该单元格突出显示。但是当 viewController 出现时,它的属性为 nil。所以,我的问题是:

模态视图 Controller 如何记住它的属性?

最佳答案

基本问题是您混合了模型和 View Controller 的职责。

记住应用程序状态是模型的责任。 View Controller 负责将数据绑定(bind)到 View 并验证用户输入。

问题是每个人都作弊。当 View Controller 中有临时状态更改时,通常不需要将其分解为模型,因为 View Controller 和状态数据具有相同的生命周期。

在您的情况下,状态数据的生命周期比 View Controller 更长。将该数据分解为一个模型,然后将该模型应用到 View Controller (单例、从持久存储中读取、在 segue 中应用、……:有很多方法可以做到这一点)。


根据您提供的少量信息,我可以想到如何实现这一目标。

有一个包含数组allItemscurrentItemscountries 的模型。有一个 currentCountry 属性。覆盖 -setCurrentCountry: 以重建 currentItems

- (void)setCurrentCountry:(MyCountryModel *)currentCountry
{
_currentCountry = currentCountry;
self.currentItems = [self filterAllItemsByCountry:currentCountry];
}

项目 View Controller 将包含模型的一个实例。当国家 View Controller 被推送时,模型可以在 segue 中传递。 countries View Controller 将使用 countries 作为它的数据源。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell = …

MyCountryModel *country = self.model.countries[indexPath.row];

cell.selected = country == self.model.currentCountry;

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCountryModel *country = self.model.countries[indexPath.row];

self.model.currentCountry = country;
}

关于iOS:模态 viewController 如何记住它的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656050/

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